Renommage Fuel Advisor (titre, header, favicon SVG/PNG, apple-touch-icon, logo SVG servis localement). Oracle: contrainte de penalty corrigee (portee inversee), quantites non entieres ecartees avant rejeu, double comptage de penalite supprime. Audit economique regenerer: plafonds omniscients coherents et positifs; deux lignes non resolues conservees telles quelles.
648 lines
28 KiB
Python
Executable File
648 lines
28 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Conseiller carburant : prix publics, profils explicites et décisions prudentes."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import io
|
||
import json
|
||
import logging
|
||
import os
|
||
import sqlite3
|
||
import statistics
|
||
import threading
|
||
import time
|
||
import urllib.parse
|
||
import urllib.request
|
||
import zipfile
|
||
from dataclasses import dataclass
|
||
from datetime import datetime, timezone
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
from pathlib import Path
|
||
from xml.etree import ElementTree as ET
|
||
|
||
import brands
|
||
import collector
|
||
import forecast
|
||
import market
|
||
import promotions
|
||
import quantity
|
||
import routing
|
||
import scheduler
|
||
import storage
|
||
import synthesis
|
||
from decision import recommend
|
||
|
||
APP_DIR = Path(__file__).resolve().parent
|
||
DATA_DIR = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor"))
|
||
CACHE_DB = DATA_DIR / "fuel.sqlite3"
|
||
HOST = os.environ.get("FUEL_ADVISOR_HOST", "0.0.0.0")
|
||
PORT = int(os.environ.get("FUEL_ADVISOR_PORT", "8003"))
|
||
FUEL_URL = os.environ.get("FUEL_PRICES_URL", "https://donnees.roulez-eco.fr/opendata/instantane")
|
||
MARKET_URL = os.environ.get("FUEL_MARKET_URL", "https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv")
|
||
CACHE_TTL = int(os.environ.get("FUEL_CACHE_TTL", "21600"))
|
||
USER_AGENT = "CortexFuelAdvisor/0.2 (+internal homelab)"
|
||
FUEL_TYPES = storage.FUELS
|
||
DEFAULT_FUEL = os.environ.get("FUEL_DEFAULT_TYPE", "Gazole")
|
||
FETCH_LOCK = threading.Lock()
|
||
LOG = logging.getLogger("fuel-advisor")
|
||
|
||
|
||
@dataclass
|
||
class Station:
|
||
id: str
|
||
name: str
|
||
address: str
|
||
city: str
|
||
lat: float
|
||
lon: float
|
||
price: float
|
||
updated: str
|
||
distance_km: float # distance à vol d'oiseau : préfiltre interne
|
||
road: str = ""
|
||
brand: str | None = None
|
||
route_distance_km: float | None = None # distance routière réelle
|
||
route_duration_min: float | None = None # durée statique (hors trafic)
|
||
route_provider: str = "none"
|
||
route_duration_label: str = "hors trafic"
|
||
route_eta_min: float | None = None # ETA de trafic, seulement si fraîche
|
||
route_eta_age_seconds: int | None = None
|
||
navigation: dict | None = None # liens d'itinéraire (Google Maps, Waze)
|
||
|
||
|
||
def detour_context(stations, vehicle, price_now):
|
||
"""Détour **marginal** de la station recommandée : km en plus par rapport à la plus proche.
|
||
|
||
C'est le coût réel du choix de station, déduit du gain attendu. Il ne dépend pas de la
|
||
destination d'un trajet éventuel : on compare simplement aller à la station recommandée plutôt
|
||
qu'à la plus proche.
|
||
"""
|
||
distances = [(station.route_distance_km, station) for station in stations if station.route_distance_km]
|
||
if not distances or not vehicle or not price_now:
|
||
return None
|
||
nearest_km, _nearest = min(distances, key=lambda item: item[0])
|
||
chosen = stations[0] if stations else _nearest
|
||
chosen_km = chosen.route_distance_km or nearest_km
|
||
extra = max(0.0, round(chosen_km - nearest_km, 1))
|
||
cost = round(extra * vehicle["consumption"] / 100 * price_now, 2)
|
||
return dict(
|
||
extra_km=extra,
|
||
nearest_km=round(nearest_km, 1),
|
||
chosen_km=round(chosen_km, 1),
|
||
cost_eur=cost,
|
||
consumption=vehicle["consumption"],
|
||
price=price_now,
|
||
basis="distance routière supplémentaire par rapport à la station la plus proche",
|
||
summary=(
|
||
f"Détour : {extra:g} km de plus que la station la plus proche, soit "
|
||
f"environ {cost:.2f} € de carburant."
|
||
),
|
||
)
|
||
|
||
|
||
def navigation_links(lat, lon):
|
||
"""Liens officiels d'itinéraire vers une coordonnée exacte de station."""
|
||
coords = f"{lat:.6f},{lon:.6f}"
|
||
return dict(
|
||
google_maps=f"https://www.google.com/maps/dir/?api=1&destination={coords}&travelmode=driving",
|
||
waze=f"https://waze.com/ul?ll={coords}&navigate=yes",
|
||
coordinates=coords,
|
||
)
|
||
|
||
|
||
def now_iso():
|
||
return datetime.now(timezone.utc).isoformat()
|
||
|
||
|
||
def ensure_db():
|
||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||
with sqlite3.connect(CACHE_DB, timeout=20) as db:
|
||
db.execute(
|
||
"CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT NOT NULL, ts INTEGER NOT NULL)"
|
||
)
|
||
|
||
|
||
def cache_get(key, ttl=CACHE_TTL):
|
||
ensure_db()
|
||
with sqlite3.connect(CACHE_DB, timeout=20) as db:
|
||
row = db.execute("SELECT value,ts FROM cache WHERE key=?", (key,)).fetchone()
|
||
if not row or time.time() - row[1] > ttl:
|
||
return None
|
||
return json.loads(row[0])
|
||
|
||
|
||
def cache_set(key, value):
|
||
ensure_db()
|
||
with sqlite3.connect(CACHE_DB, timeout=20) as db:
|
||
db.execute(
|
||
"REPLACE INTO cache VALUES(?,?,?)", (key, json.dumps(value, ensure_ascii=False), int(time.time()))
|
||
)
|
||
|
||
|
||
def fetch_bytes(url, timeout=20):
|
||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||
raw = response.read(50_000_001)
|
||
if len(raw) > 50_000_000:
|
||
raise ValueError("Source trop volumineuse")
|
||
return raw
|
||
|
||
|
||
def load_fuel_data(force=False):
|
||
with FETCH_LOCK:
|
||
cached = None if force else cache_get("fuel_data")
|
||
if cached is not None:
|
||
return cached
|
||
raw = fetch_bytes(FUEL_URL, 45)
|
||
if raw[:2] == b"PK":
|
||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||
name = next(n for n in archive.namelist() if n.lower().endswith(".xml"))
|
||
if archive.getinfo(name).file_size > 100_000_000:
|
||
raise ValueError("Archive trop volumineuse")
|
||
raw = archive.read(name)
|
||
root = ET.fromstring(raw)
|
||
rows = []
|
||
for pdv in root.findall(".//pdv"):
|
||
try:
|
||
lat = storage.number(float(pdv.attrib["latitude"]) / 100000, "Latitude", -90, 90)
|
||
lon = storage.number(float(pdv.attrib["longitude"]) / 100000, "Longitude", -180, 180)
|
||
except (ValueError, KeyError):
|
||
continue
|
||
prices, updates = {}, {}
|
||
ruptures = {r.attrib.get("nom") for r in pdv.findall("rupture") if not r.attrib.get("fin")}
|
||
for prix in pdv.findall("prix"):
|
||
fuel = prix.attrib.get("nom")
|
||
if fuel not in FUEL_TYPES or fuel in ruptures:
|
||
continue
|
||
try:
|
||
value = float(prix.attrib["valeur"])
|
||
value = value / 1000 if value > 10 else value
|
||
prices[fuel] = storage.number(value, "Prix", 0.01, 10)
|
||
updates[fuel] = prix.attrib.get("maj", "")
|
||
except (ValueError, KeyError):
|
||
continue
|
||
if prices:
|
||
rows.append(
|
||
dict(
|
||
road="autoroute" if str(pdv.attrib.get("pop", "")).upper() == "A" else "",
|
||
id=pdv.attrib.get("id", ""),
|
||
name=pdv.findtext("adresse", "Station-service"),
|
||
address=pdv.findtext("adresse", ""),
|
||
city=pdv.findtext("ville", ""),
|
||
lat=lat,
|
||
lon=lon,
|
||
prices=prices,
|
||
updates=updates,
|
||
)
|
||
)
|
||
if not rows:
|
||
raise ValueError("Aucune station exploitable dans la source")
|
||
cache_set("fuel_data", rows)
|
||
return rows
|
||
|
||
|
||
haversine = storage.distance_km
|
||
|
||
|
||
def candidate_stations(lat, lon, fuel, radius_km):
|
||
"""Préfiltre rapide à vol d'oiseau, volontairement plus large que le rayon demandé.
|
||
|
||
La route est toujours plus longue que la ligne droite : ce préfiltre évite de calculer
|
||
un itinéraire pour des stations lointaines sans en écarter de plausibles.
|
||
"""
|
||
factor = float(os.environ.get("FUEL_PREFILTER_FACTOR", "1.6"))
|
||
candidates = []
|
||
for row in load_fuel_data():
|
||
if fuel not in row["prices"] or not storage.fresh_price(row["updates"].get(fuel, "")):
|
||
continue
|
||
air = haversine(lat, lon, row["lat"], row["lon"])
|
||
if air <= radius_km * factor:
|
||
candidates.append((row, air))
|
||
candidates.sort(key=lambda item: item[1])
|
||
limit = int(os.environ.get("FUEL_ROUTING_MAX_TARGETS", "60"))
|
||
return candidates[:limit]
|
||
|
||
|
||
def nearest_stations(lat, lon, fuel, radius_km, routing_enabled=True, origin_tag=None):
|
||
"""Rayon appliqué à la **distance routière** ; le vol d'oiseau ne sert que de préfiltre."""
|
||
candidates = candidate_stations(lat, lon, fuel, radius_km)
|
||
routes, routing_info = {}, dict(provider="none", computed=0, from_cache=0, failures=[], note="")
|
||
if candidates and routing_enabled:
|
||
try:
|
||
routes, routing_info = routing.routes(
|
||
(lat, lon),
|
||
[(row["id"], row["lat"], row["lon"]) for row, _air in candidates],
|
||
origin_tag=origin_tag,
|
||
)
|
||
except Exception as exc:
|
||
LOG.warning("Calcul d'itinéraire impossible : %s", type(exc).__name__)
|
||
routing_info = dict(
|
||
provider="none",
|
||
computed=0,
|
||
from_cache=0,
|
||
failures=[type(exc).__name__],
|
||
note="Service de routage indisponible.",
|
||
)
|
||
stations = []
|
||
for row, air in candidates:
|
||
route = routes.get(row["id"])
|
||
if routes:
|
||
if not route:
|
||
continue # pas d'itinéraire connu : aucune distance approximée présentée
|
||
if route["distance_km"] > radius_km:
|
||
continue # le rayon porte bien sur la distance routière
|
||
elif air > radius_km:
|
||
continue # sans routage, repli explicite sur le vol d'oiseau (signalé à l'écran)
|
||
stations.append(
|
||
Station(
|
||
id=row["id"],
|
||
name=row["name"] or "Station-service",
|
||
address=row["address"],
|
||
city=row["city"],
|
||
lat=row["lat"],
|
||
lon=row["lon"],
|
||
price=row["prices"][fuel],
|
||
updated=row["updates"].get(fuel, ""),
|
||
distance_km=round(air, 1),
|
||
road=row.get("road", ""),
|
||
route_distance_km=route["distance_km"] if route else None,
|
||
route_duration_min=route["duration_min"] if route else None,
|
||
route_provider=route["provider"] if route else "none",
|
||
route_duration_label=route.get("duration_label", "hors trafic") if route else "hors trafic",
|
||
route_eta_min=route.get("eta_min") if route else None,
|
||
route_eta_age_seconds=route.get("eta_age_seconds") if route else None,
|
||
navigation=navigation_links(row["lat"], row["lon"]),
|
||
)
|
||
)
|
||
return sorted(
|
||
stations,
|
||
key=lambda s: (s.price, s.route_distance_km if s.route_distance_km is not None else s.distance_km),
|
||
), routing_info
|
||
|
||
|
||
def _synthesis(fuel):
|
||
"""Synthèse amont explicable ; une erreur de calcul ne doit jamais casser le conseil."""
|
||
try:
|
||
return synthesis.build(fuel)
|
||
except Exception as exc:
|
||
LOG.warning("Synthèse amont indisponible : %s", type(exc).__name__)
|
||
return dict(
|
||
pressure="INCERTAINE",
|
||
pressure_key="unknown",
|
||
confidence=None,
|
||
factors=[],
|
||
plain="Synthèse indisponible : les données amont n’ont pas pu être lues.",
|
||
disclaimer="Aucun indicateur n’est utilisé faute de données exploitables.",
|
||
generated_at=now_iso(),
|
||
error=type(exc).__name__,
|
||
)
|
||
|
||
|
||
def market_signal(force=False):
|
||
"""Délègue au module marché (fournisseurs en chaîne, jamais de fausse stabilité)."""
|
||
return market.fetch(force=force)
|
||
|
||
|
||
def geocode_address(query):
|
||
# Une recherche non enregistrée n'est pas conservée dans le cache SQL.
|
||
params = urllib.parse.urlencode(dict(q=query, format="jsonv2", limit=1, countrycodes="fr"))
|
||
rows = json.loads(fetch_bytes("https://nominatim.openstreetmap.org/search?" + params, 12))
|
||
if not rows:
|
||
raise ValueError("Adresse introuvable")
|
||
return dict(
|
||
lat=float(rows[0]["lat"]), lon=float(rows[0]["lon"]), label=rows[0].get("display_name", query)
|
||
)
|
||
|
||
|
||
def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None):
|
||
# Flux instantané : actualisation forcée si le dernier téléchargement a plus de 15 minutes.
|
||
try:
|
||
refresh = collector.ensure_fresh_local(int(os.environ.get("FUEL_LOCAL_MAX_AGE", "900")))
|
||
except Exception as exc:
|
||
LOG.warning("Actualisation locale impossible : %s", type(exc).__name__)
|
||
refresh = dict(refreshed=False, error=type(exc).__name__)
|
||
stations, error = [], None
|
||
routing_info = dict(provider="none", computed=0, from_cache=0, failures=[], note="")
|
||
# Une position de téléphone varie de quelques dizaines de mètres : l'origine est rattachée au
|
||
# favori correspondant pour que le cache de routes reste stable, sinon arrondie à ~100 m.
|
||
origin_tag = None
|
||
try:
|
||
favorite = storage.match_favorite(lat, lon)
|
||
if favorite:
|
||
origin_tag = f"fav:{favorite['id']}"
|
||
except Exception:
|
||
LOG.warning("Rapprochement du favori ignoré")
|
||
try:
|
||
stations, routing_info = nearest_stations(lat, lon, fuel, radius_km, origin_tag=origin_tag)
|
||
except Exception as exc:
|
||
LOG.warning("Source des prix inaccessible : %s", type(exc).__name__)
|
||
error = "Source des prix inaccessible ; aucun ancien prix présenté comme actuel."
|
||
# Complète les noms manquants depuis le flux déjà téléchargé (aucun accès réseau ici).
|
||
try:
|
||
cached_flux = cache_get("fuel_data")
|
||
if cached_flux:
|
||
storage.sync_station_names(cached_flux)
|
||
except Exception:
|
||
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])
|
||
brands_known = [(item["id"], item["brand"]) for item in enriched if item.get("brand")]
|
||
if brands_known:
|
||
storage.set_brands(brands_known)
|
||
hist = storage.history(lat, lon, radius_km, fuel)
|
||
result = recommend(vehicle, remaining_km, hist, trip)
|
||
# Quantité à acheter : stock optimisé à partir du besoin réel et de la prévision validée.
|
||
price_now = stations[0].price if stations else None
|
||
# Deux distributions distinctes, jamais mélangées : l'espace (aujourd'hui) et le temps (passé).
|
||
try:
|
||
local_position = storage.local_position(lat, lon, radius_km, fuel)
|
||
except Exception:
|
||
LOG.warning("Position locale indisponible")
|
||
local_position = dict(
|
||
kind="local", percentile=None, stations=0, summary="Position locale indisponible."
|
||
)
|
||
try:
|
||
historical_position = storage.historical_position(lat, lon, radius_km, fuel)
|
||
except Exception:
|
||
LOG.warning("Position historique indisponible")
|
||
historical_position = dict(
|
||
kind="historique", percentile=None, windows={}, summary="Position historique indisponible."
|
||
)
|
||
detour = detour_context(stations, vehicle, price_now)
|
||
out_look = forecast.outlook(fuel)
|
||
stock = quantity.plan(
|
||
vehicle,
|
||
remaining_km,
|
||
price_now=price_now,
|
||
local_position=local_position,
|
||
historical_position=historical_position,
|
||
outlook=out_look,
|
||
trip=trip,
|
||
detour=detour,
|
||
)
|
||
result.update(
|
||
quantity=stock,
|
||
quantity_headline=quantity.headline(stock),
|
||
local_position=local_position,
|
||
historical_position=historical_position,
|
||
detour=detour,
|
||
forecast=out_look,
|
||
)
|
||
prices = [s.price for s in stations]
|
||
stats = {}
|
||
if prices:
|
||
stats = dict(
|
||
count=len(prices),
|
||
best=prices[0],
|
||
min=min(prices),
|
||
max=max(prices),
|
||
average=round(statistics.mean(prices), 3),
|
||
median=round(statistics.median(prices), 3),
|
||
best_tie_count=prices.count(prices[0]),
|
||
price_buckets=[dict(price=p, count=prices.count(p)) for p in sorted(set(prices))],
|
||
)
|
||
result.update(
|
||
generated_at=now_iso(),
|
||
fuel=fuel,
|
||
history=hist,
|
||
local_stats=stats,
|
||
stations=enriched[:12],
|
||
market=market_signal(),
|
||
ai_used=False,
|
||
brands_source="OpenStreetMap via Nominatim" if brands_known else None,
|
||
brands_warning=None
|
||
if brands_known
|
||
else "Enseignes indisponibles pour cette zone (source OpenStreetMap muette).",
|
||
price_warning=error
|
||
or (None if prices else "Aucun prix déclaré depuis moins de 7 jours dans ce rayon."),
|
||
summary="Le choix de la station et le moment de ravitaillement sont évalués séparément.",
|
||
routing=routing_info,
|
||
origin_tag=origin_tag,
|
||
distance_note=(
|
||
"Distances routières réelles en voiture, calculées depuis votre position"
|
||
+ (
|
||
f" (fournisseur {routing_info['provider']})"
|
||
if routing_info.get("provider") not in (None, "none")
|
||
else ""
|
||
)
|
||
+ ". Le détour peut annuler l’économie."
|
||
if routing_info.get("provider") not in (None, "none")
|
||
else "Routage indisponible : les distances affichées restent à vol d’oiseau et le rayon "
|
||
"porte sur cette distance. Le détour peut annuler l’économie."
|
||
),
|
||
detour_prep=dict(
|
||
available=any(s.route_distance_km is not None for s in stations),
|
||
note="Distance et durée routières enregistrées pour chaque station : de quoi calculer "
|
||
"plus tard le coût réel du détour (gain sur le plein moins le carburant consommé "
|
||
"pour y aller). Aucune décision n’est prise sur cette base pour l’instant.",
|
||
),
|
||
upstream_synthesis=_synthesis(fuel),
|
||
price_max_age_days=storage.MAX_PRICE_AGE_DAYS,
|
||
local_refresh=refresh,
|
||
promotions=promotions.active()[:12],
|
||
promotions_note="Une opération annoncée n’est pas forcément la moins chère : "
|
||
"comparez son tarif estimé aux autres stations du rayon.",
|
||
)
|
||
return result
|
||
|
||
|
||
def from_payload(data):
|
||
lat = storage.number(data.get("lat"), "Latitude", -90, 90)
|
||
lon = storage.number(data.get("lon"), "Longitude", -180, 180)
|
||
radius = storage.number(data.get("radius_km", 15), "Rayon", 1, 80)
|
||
vehicle = storage.get_entity("vehicles", int(data["vehicle_id"])) if data.get("vehicle_id") else None
|
||
fuel = vehicle["fuel"] if vehicle else data.get("fuel", DEFAULT_FUEL)
|
||
if fuel not in FUEL_TYPES:
|
||
raise ValueError("Carburant non supporté")
|
||
trip = data.get("trip")
|
||
if trip is not None and not isinstance(trip, dict):
|
||
raise ValueError("Trajet invalide")
|
||
return advice(lat, lon, fuel, radius, vehicle, data.get("remaining_km"), trip)
|
||
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
def setup(self):
|
||
super().setup()
|
||
self.connection.settimeout(70)
|
||
|
||
def log_message(self, fmt, *args):
|
||
# Pas de query string (géolocalisation/adresse), ni de corps de requête dans les logs.
|
||
LOG.info("%s %s", self.command, urllib.parse.urlparse(self.path).path)
|
||
|
||
def send_body(self, body, content_type, status=200):
|
||
self.send_response(status)
|
||
self.send_header("Content-Type", content_type)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.send_header("Cache-Control", "no-store")
|
||
self.send_header("X-Content-Type-Options", "nosniff")
|
||
self.send_header("Referrer-Policy", "same-origin")
|
||
self.send_header(
|
||
"Content-Security-Policy",
|
||
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'",
|
||
)
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
|
||
def send_json(self, payload, status=200):
|
||
self.send_body(
|
||
json.dumps(payload, ensure_ascii=False, allow_nan=False).encode(),
|
||
"application/json; charset=utf-8",
|
||
status,
|
||
)
|
||
|
||
# Assets servis localement : aucun appel distant au moment du rendu. Les images sont
|
||
# mises en cache côté client, les pages restent revalidées pour ne pas figer l'interface.
|
||
STATIC_FILES = {
|
||
"/": "text/html; charset=utf-8",
|
||
"/index.html": "text/html; charset=utf-8",
|
||
"/ui.js": "text/javascript; charset=utf-8",
|
||
"/style.css": "text/css; charset=utf-8",
|
||
"/logo.svg": "image/svg+xml",
|
||
"/favicon.svg": "image/svg+xml",
|
||
"/favicon-32.png": "image/png",
|
||
"/favicon-16.png": "image/png",
|
||
"/apple-touch-icon.png": "image/png",
|
||
}
|
||
|
||
def do_GET(self):
|
||
try:
|
||
parsed = urllib.parse.urlparse(self.path)
|
||
path = parsed.path
|
||
q = {k: v[0] for k, v in urllib.parse.parse_qs(parsed.query).items()}
|
||
if path == "/healthz":
|
||
return self.send_json(dict(ok=True, version=2, time=now_iso()))
|
||
if path in self.STATIC_FILES:
|
||
name = "index.html" if path == "/" else path.lstrip("/")
|
||
return self.send_body((APP_DIR / name).read_bytes(), self.STATIC_FILES[path])
|
||
if path == "/api/config":
|
||
return self.send_json(dict(fuels=FUEL_TYPES, default_fuel=DEFAULT_FUEL))
|
||
if path == "/api/status":
|
||
return self.send_json(collector.status())
|
||
if path == "/api/jobs":
|
||
return self.send_json(
|
||
dict(
|
||
jobs=scheduler.inventory(),
|
||
llm_queue=storage.llm_queue(),
|
||
note="Inventaire des collecteurs : source, fréquence, dernière exécution réussie, "
|
||
"dernière observation disponible, prochaine exécution et état.",
|
||
)
|
||
)
|
||
if path == "/api/promotions":
|
||
return self.send_json(
|
||
dict(
|
||
items=promotions.active()[:40],
|
||
note="Opérations annoncées ou en cours, avec leur source.",
|
||
)
|
||
)
|
||
if path == "/api/upstream":
|
||
return self.send_json(
|
||
dict(
|
||
series=storage.latest_upstream(),
|
||
history={
|
||
name: storage.upstream_series(name, int(q.get("days", 400)))
|
||
for name in (
|
||
"dgec_brent_usd",
|
||
"brent_usd_daily",
|
||
"brent_eur_daily",
|
||
"usd_per_eur",
|
||
"dgec_margin_usd_per_bbl",
|
||
"dgec_margin_eur_per_tonne",
|
||
"fr_ttc_Gazole",
|
||
"fr_htt_Gazole",
|
||
"fr_ttc_E10",
|
||
"fr_htt_E10",
|
||
"eu_fr_diesel_ttc",
|
||
"eu_fr_diesel_htt",
|
||
)
|
||
},
|
||
chokepoints=storage.chokepoint_daily(int(q.get("chokepoint_days", 60))),
|
||
note="Sources amont officielles. Chaque valeur porte sa date et sa source ; "
|
||
"une donnée absente reste inconnue, jamais supposée stable.",
|
||
)
|
||
)
|
||
if path in ("/api/vehicles", "/api/favorites"):
|
||
return self.send_json(dict(items=storage.list_entities(path.split("/")[-1])))
|
||
if path == "/api/geocode":
|
||
query = q.get("q", "").strip()
|
||
if not 2 <= len(query) <= 200:
|
||
raise ValueError("Adresse requise, 200 caractères maximum")
|
||
return self.send_json(geocode_address(query))
|
||
if path == "/api/advice":
|
||
# Compatibilité comparaison publique, autonomie seulement via POST.
|
||
q.pop("vehicle_id", None)
|
||
return self.send_json(from_payload(q))
|
||
if path == "/api/history":
|
||
lat = storage.number(q.get("lat"), "Latitude", -90, 90)
|
||
lon = storage.number(q.get("lon"), "Longitude", -180, 180)
|
||
radius = storage.number(q.get("radius_km", 15), "Rayon", 1, 80)
|
||
fuel = q.get("fuel", DEFAULT_FUEL)
|
||
if fuel not in FUEL_TYPES:
|
||
raise ValueError("Carburant invalide")
|
||
return self.send_json(storage.history(lat, lon, radius, fuel))
|
||
return self.send_json(dict(error="Route introuvable"), 404)
|
||
except Exception as exc:
|
||
self.handle_error(exc)
|
||
|
||
def handle_error(self, exc):
|
||
if isinstance(exc, (ValueError, TypeError)):
|
||
self.send_json(dict(error=str(exc)), 400)
|
||
elif isinstance(exc, LookupError):
|
||
self.send_json(dict(error=str(exc)), 404)
|
||
else:
|
||
LOG.exception("Erreur de traitement")
|
||
self.send_json(dict(error="Service temporairement indisponible"), 503)
|
||
|
||
def mutation(self):
|
||
try:
|
||
origin = self.headers.get("Origin")
|
||
if self.headers.get("X-Fuel-Request") != "1" or (
|
||
origin and urllib.parse.urlparse(origin).netloc != self.headers.get("Host")
|
||
):
|
||
return self.send_json(dict(error="Requête externe refusée"), 403)
|
||
content_type = self.headers.get("Content-Type", "").split(";")[0].strip()
|
||
if content_type and content_type != "application/json":
|
||
return self.send_json({"error": "Content-Type application/json requis"}, 415)
|
||
length = int(self.headers.get("Content-Length", 0))
|
||
if not 0 <= length <= 16384:
|
||
return self.send_json({"error": "Requête trop volumineuse"}, 413)
|
||
if length and content_type != "application/json":
|
||
return self.send_json({"error": "Content-Type application/json requis"}, 415)
|
||
data = json.loads(self.rfile.read(length)) if length else {}
|
||
if not isinstance(data, dict):
|
||
raise ValueError("Objet JSON attendu")
|
||
path = urllib.parse.urlparse(self.path).path
|
||
if path == "/api/advice" and self.command == "POST":
|
||
return self.send_json(from_payload(data))
|
||
if path == "/api/collect" and self.command == "POST":
|
||
result = collector.collect(force=True)
|
||
return self.send_json(result, 503 if result["status"] == "error" else 200)
|
||
parts = path.strip("/").split("/")
|
||
if len(parts) not in (2, 3) or parts[0] != "api" or parts[1] not in ("vehicles", "favorites"):
|
||
return self.send_json(dict(error="Route introuvable"), 404)
|
||
entity_id = int(parts[2]) if len(parts) == 3 else None
|
||
if self.command == "POST" and entity_id is None:
|
||
result = storage.save_entity(parts[1], data)
|
||
return self.send_json(result, 201)
|
||
if self.command == "PUT" and entity_id is not None:
|
||
return self.send_json(storage.save_entity(parts[1], data, entity_id))
|
||
if self.command == "DELETE" and entity_id is not None:
|
||
storage.delete_entity(parts[1], entity_id)
|
||
return self.send_json(dict(ok=True))
|
||
return self.send_json(dict(error="Méthode non autorisée"), 405)
|
||
except Exception as exc:
|
||
self.handle_error(exc)
|
||
|
||
do_POST = mutation
|
||
do_PUT = mutation
|
||
do_DELETE = mutation
|
||
|
||
|
||
def main():
|
||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||
ensure_db()
|
||
LOG.info("Fuel advisor v2 écoute sur %s:%s", HOST, PORT)
|
||
ThreadingHTTPServer((HOST, PORT), Handler).serve_forever()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|