Files
Fuel-Advisor/app.py
root a2434836c4 Historiser les sources amont officielles (DGEC, bulletin UE, detroits IMF)
Nouveau module upstream : parseurs testables des xlsx DGEC (Brent mensuel, marge brute de raffinage, prix HTT et TTC France par carburant) et du bulletin petrolier europeen (France TTC et hors taxes), plus les passages quotidiens par detroit via IMF PortWatch utilise par l IEA. Historisation idempotente dans upstream_series, chokepoint_daily et upstream_runs, collecte amont independante des favoris et endpoint /api/upstream. Chaque valeur porte date, source et fraicheur reelle.
2026-09-12 22:27:58 +02:00

423 lines
18 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 market
import storage
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
road: str = ""
brand: str | None = None
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 nearest_stations(lat, lon, fuel, radius_km):
stations = []
for row in load_fuel_data():
if fuel not in row["prices"] or not storage.fresh_price(row["updates"].get(fuel, "")):
continue
distance = haversine(lat, lon, row["lat"], row["lon"])
if distance <= radius_km:
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(distance, 1),
road=row.get("road", ""),
)
)
return sorted(stations, key=lambda s: (s.price, s.distance_km))
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):
stations, error = [], None
try:
stations = nearest_stations(lat, lon, fuel, radius_km)
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)
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.",
distance_note="Distances à vol d’oiseau, pas des trajets routiers. Le détour peut annuler l’économie.",
price_max_age_days=storage.MAX_PRICE_AGE_DAYS,
)
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,
)
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 ("/", "/index.html", "/ui.js", "/style.css"):
name = "index.html" if path in ("/", "/index.html") else path[1:]
content_type = {
"index.html": "text/html; charset=utf-8",
"ui.js": "text/javascript; charset=utf-8",
"style.css": "text/css; charset=utf-8",
}[name]
return self.send_body((APP_DIR / name).read_bytes(), content_type)
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/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()