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:
114
enseignes.py
Normal file
114
enseignes.py
Normal 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"
|
||||
Reference in New Issue
Block a user