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.
This commit is contained in:
root
2026-09-13 12:28:41 +02:00
parent 7bb7778c55
commit 726bc25fb0
5 changed files with 168 additions and 3 deletions

19
app.py
View File

@@ -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):

23
brands.svg Normal file
View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">
<symbol id="brand-totalenergies" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1d4ed8"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">T</text></symbol>
<symbol id="brand-total-access" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1d4ed8"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">T</text></symbol>
<symbol id="brand-total" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1d4ed8"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">T</text></symbol>
<symbol id="brand-intermarche" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#c2410c"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">I</text></symbol>
<symbol id="brand-e-leclerc" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#0f766e"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">L</text></symbol>
<symbol id="brand-carrefour" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1e40af"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">C</text></symbol>
<symbol id="brand-carrefour-market" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#1e40af"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">C</text></symbol>
<symbol id="brand-auchan" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#b91c1c"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">A</text></symbol>
<symbol id="brand-super-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-systeme-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-station-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-u" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#15803d"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">U</text></symbol>
<symbol id="brand-esso-express" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#7c2d12"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">E</text></symbol>
<symbol id="brand-esso" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#7c2d12"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">E</text></symbol>
<symbol id="brand-avia" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#0369a1"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">A</text></symbol>
<symbol id="brand-shell" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#a16207"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">S</text></symbol>
<symbol id="brand-elan" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#4d7c0f"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">E</text></symbol>
<symbol id="brand-monoprix" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#7e22ce"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">M</text></symbol>
<symbol id="brand-spar" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#166534"/><text x="20" y="27" text-anchor="middle" font-family="system-ui,sans-serif" font-size="21" font-weight="700" fill="#ffffff">S</text></symbol>
<symbol id="brand-inconnue" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="#475569"/><path d="M12 9h11a3 3 0 0 1 3 3v20H9V12a3 3 0 0 1 3-3z" fill="#ffffff"/><rect x="14" y="13" width="7" height="6" rx="1.5" fill="#475569"/><path d="M26 14h2.6a2 2 0 0 1 2 2v6.5a1.8 1.8 0 0 0 3.6 0V17" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round"/><rect x="16" y="30" width="14" height="2.6" rx="1.3" fill="#cbd5e1"/></symbol>
</svg>

After

Width:  |  Height:  |  Size: 5.1 KiB

114
enseignes.py Normal file
View File

@@ -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"

View File

@@ -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}

10
ui.js
View File

@@ -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 `<svg class="brand-tile" role="img" aria-label="${esc(label||'Enseigne')}"><use href="/brands.svg#brand-${known}"></use></svg>`;
}
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 `<div class="station-card compact-station${index===0?' best':''}">
<div class="station-head"><strong>${esc(s.brand||s.name)}</strong><span>${num(s.price,3)} €<small>/L</small></span></div>
<div class="station-head">${brandTile(s.brand_slug,s.brand||s.name)}<strong>${esc(s.brand||s.name)}</strong><span>${num(s.price,3)} €<small>/L</small></span></div>
<p class="hint">${esc(s.city||'')}${km!==null&&km!==undefined?` · ${num(km,1)} km${extra?` (détour ≈ ${num(extra,1)} km)`:''}`:' · distance inconnue'}</p>
<p class="hint">Prix déclaré : ${esc(s.updated)}${index===0?' · <strong>meilleur choix</strong>':''}</p>
</div>`;
@@ -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?`<div class="nav-actions"><a class="nav-btn" href="${esc(s.navigation.google_maps)}" target="_blank" rel="noopener">Google Maps</a><a class="nav-btn" href="${esc(s.navigation.waze)}" target="_blank" rel="noopener">Waze</a></div>`:'';
return `<div class="station"><div>${s.brand?`<span class="badge brand">${esc(s.brand)}</span>`:'<span class="badge">Enseigne inconnue</span>'}${s.road?`<span class="badge">${esc(s.road)}</span>`:''}<strong>${esc(s.name)}</strong><p class="hint">${esc(s.city)} · ${distance}</p><p class="hint">Déclaré : ${esc(s.updated)}</p>${nav}</div><div class="price">${num(s.price,3)} <small>€/L</small></div></div>`;}).join('');
return `<div class="station"><div>${s.brand?`<span class="badge brand">${brandTile(s.brand_slug,s.brand)}${esc(s.brand)}</span>`:'<span class="badge brand">Enseigne inconnue</span>'}${s.road?`<span class="badge">${esc(s.road)}</span>`:''}<strong>${esc(s.name)}</strong><p class="hint">${esc(s.city)} · ${distance}</p><p class="hint">Déclaré : ${esc(s.updated)}</p>${nav}</div><div class="price">${num(s.price,3)} <small>€/L</small></div></div>`;}).join('');
const reasons=d.reasons.map(r=>`<li>${esc(r)}</li>`).join('');
const metrics=d.usable_km!==null?`<div class="metrics"><div class="metric"><strong>${num(d.usable_km)} km</strong><span>avant votre marge</span></div><div class="metric"><strong>${d.days_left===null?'Occasionnel':num(d.days_left,1)+' j'}</strong><span>${d.days_left===null?'pas de moyenne imposée':'usage moyen estimé'}</span></div><div class="metric"><strong>${d.topup_liters===null?'—':num(d.topup_liters,1)+' L'}</strong><span>appoint indicatif</span></div></div>`:'';
$('result').innerHTML=`<section class="card hero tone-${esc(d.action)}"><div class="eyebrow">Conseil Fuel Advisor · ${esc(d.fuel)}</div><h2 class="verdict">${esc(decisionLabel(d.action))}</h2><p class="hero-quantity">${esc(heroQuantity(d))}</p>${heroTrend(d)}<p class="hint">${esc(d.quantity_headline||d.label)}</p><details><summary>Pourquoi ce conseil ?</summary>${quantityBlock(d)}<ul class="reasons">${reasons}</ul></details><div class="tags"><span>Sans décision par IA</span><span>Aucun signal prédictif utilisé dans le conseil</span>${fresh}</div></section>