Files
Fuel-Advisor/storage.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

499 lines
20 KiB
Python
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.
"""Persistance locale : profils explicites et observations publiques quotidiennes."""
from __future__ import annotations
import json
import math
import os
import sqlite3
import statistics
from contextlib import contextmanager
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from zoneinfo import ZoneInfo
PARIS = ZoneInfo("Europe/Paris")
MAX_PRICE_AGE_DAYS = 7
def fresh_price(updated, now=None):
now = now or datetime.now(timezone.utc)
try:
stamp = datetime.fromisoformat(updated)
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=PARIS)
return timedelta(hours=-1) <= now - stamp <= timedelta(days=MAX_PRICE_AGE_DAYS)
except (ValueError, TypeError):
return False
def distance_km(lat, lon, other_lat, other_lon):
p1, p2 = math.radians(lat), math.radians(other_lat)
dlat, dlon = p2 - p1, math.radians(other_lon - lon)
a = math.sin(dlat / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlon / 2) ** 2
return 6371 * 2 * math.asin(math.sqrt(min(1, max(0, a))))
def record_observations(rows, now=None):
now = now or datetime.now(timezone.utc)
day = now.astimezone(PARIS).date().isoformat()
values = {}
for row in rows:
for fuel, price in row["prices"].items():
if fuel not in FUELS or not math.isfinite(price) or not 0 < price < 20:
continue
key = (row["id"], fuel, day)
values[key] = (*key, price, row["updates"].get(fuel, ""), now.isoformat(), row["lat"], row["lon"])
with connect() as db:
db.executemany(
"""INSERT INTO observations VALUES(?,?,?,?,?,?,?,?)
ON CONFLICT(station_id,fuel,day) DO UPDATE SET price=excluded.price,
source_updated=excluded.source_updated,collected_at=excluded.collected_at,
lat=excluded.lat,lon=excluded.lon""",
list(values.values()),
)
# Noms/communes/type de voie conservés une fois par station (affichage des graphiques).
seen = {
str(row["id"]): (
str(row["id"]),
str(row.get("name") or "")[:120],
str(row.get("city") or "")[:80],
str(row.get("road") or "")[:20],
row["lat"],
row["lon"],
now.isoformat(),
)
for row in rows
if row.get("id")
}
if seen:
db.executemany(
"""INSERT INTO stations VALUES(?,?,?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name,city=excluded.city,
road=excluded.road,lat=excluded.lat,lon=excluded.lon,seen_at=excluded.seen_at""",
list(seen.values()),
)
return len(values)
def sync_station_names(flux_rows, now=None):
"""Complète les noms/communes manquants à partir du flux officiel déjà téléchargé.
Utile quand la collecte du jour a été faite par une version antérieure : l'historique
affiche alors des identifiants au lieu des adresses. Aucun téléchargement ici.
"""
now = now or datetime.now(timezone.utc)
with connect() as db:
observed = {str(row[0]) for row in db.execute("SELECT DISTINCT station_id FROM observations")}
known = {
str(row[0])
for row in db.execute("SELECT id FROM stations WHERE trim(name) <> '' OR trim(city) <> ''")
}
missing = observed - known
if not missing:
return 0
rows = [
(
str(row["id"]),
str(row.get("name") or "")[:120],
str(row.get("city") or "")[:80],
str(row.get("road") or "")[:20],
row.get("lat"),
row.get("lon"),
now.isoformat(),
)
for row in flux_rows
if str(row.get("id") or "") in missing and (row.get("name") or row.get("city"))
]
if not rows:
return 0
with connect() as db:
db.executemany(
"""INSERT INTO stations VALUES(?,?,?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name,city=excluded.city,road=excluded.road,
lat=excluded.lat,lon=excluded.lon,seen_at=excluded.seen_at""",
rows,
)
return len(rows)
def save_upstream(series, rows, unit, source, now=None):
"""Historise une série amont officielle (idempotent : la même date remplace la valeur)."""
now = now or datetime.now(timezone.utc)
values = [
(str(series), str(row["day"]), float(row["value"]), str(unit), str(source), now.isoformat())
for row in rows
if row.get("day") and isinstance(row.get("value"), (int, float)) and math.isfinite(row["value"])
]
if not values:
return 0
with connect() as db:
db.executemany(
"""INSERT INTO upstream_series VALUES(?,?,?,?,?,?)
ON CONFLICT(series,day) DO UPDATE SET value=excluded.value,unit=excluded.unit,
source=excluded.source,fetched_at=excluded.fetched_at""",
values,
)
return len(values)
def save_chokepoints(entries, source, now=None):
"""Historise les passages observés par détroit (source IMF PortWatch)."""
now = now or datetime.now(timezone.utc)
values = [
(
name,
entry["day"],
entry.get("transit_tankers"),
entry.get("transit_total"),
entry.get("capacity_tankers"),
entry.get("capacity_total"),
str(source),
now.isoformat(),
)
for name, entry in (entries or {}).items()
if entry.get("day")
]
if not values:
return 0
with connect() as db:
db.executemany(
"""INSERT INTO chokepoint_daily VALUES(?,?,?,?,?,?,?,?)
ON CONFLICT(chokepoint,day) DO UPDATE SET transit_tankers=excluded.transit_tankers,
transit_total=excluded.transit_total,capacity_tankers=excluded.capacity_tankers,
capacity_total=excluded.capacity_total,source=excluded.source,fetched_at=excluded.fetched_at""",
values,
)
return len(values)
def upstream_series(name, days=None):
query = "SELECT day, value, unit, source FROM upstream_series WHERE series=?"
args = [name]
if days:
query += " AND day>=?"
args.append((datetime.now(timezone.utc) - timedelta(days=days)).date().isoformat())
with connect() as db:
rows = db.execute(query + " ORDER BY day", args).fetchall()
return [dict(day=row["day"], value=row["value"], unit=row["unit"], source=row["source"]) for row in rows]
def latest_upstream():
"""Dernière valeur connue par série, avec sa fraîcheur réelle (jamais supposée à jour)."""
with connect() as db:
rows = db.execute(
"""SELECT series, day, value, unit, source FROM upstream_series u WHERE day =
(SELECT max(day) FROM upstream_series WHERE series=u.series) ORDER BY series"""
).fetchall()
today = datetime.now(timezone.utc).date()
out = {}
for row in rows:
try:
age = (today - date.fromisoformat(row["day"])).days
except ValueError:
age = None
if age is None:
state = "unknown"
elif age <= 35:
state = "fresh"
else:
state = "seasoned" if age <= 400 else "stale"
out[row["series"]] = dict(
day=row["day"],
value=row["value"],
unit=row["unit"],
source=row["source"],
age_days=age,
freshness=state,
)
return out
def chokepoint_daily(days=60):
with connect() as db:
rows = db.execute(
"SELECT * FROM chokepoint_daily WHERE day>=? ORDER BY chokepoint, day",
((datetime.now(timezone.utc) - timedelta(days=days)).date().isoformat(),),
).fetchall()
out = {}
for row in rows:
out.setdefault(row["chokepoint"], []).append(
dict(
day=row["day"],
transit_tankers=row["transit_tankers"],
transit_total=row["transit_total"],
capacity_tankers=row["capacity_tankers"],
capacity_total=row["capacity_total"],
source=row["source"],
)
)
return out
def set_brands(pairs, now=None):
"""Mémorise les enseignes trouvées (station_id -> enseigne) sans écraser par du vide."""
now = now or datetime.now(timezone.utc)
rows = [
(str(station_id), str(brand)[:40], now.isoformat())
for station_id, brand in pairs
if station_id and brand
]
if not rows:
return 0
with connect() as db:
db.executemany(
"""INSERT INTO station_brand VALUES(?,?,?)
ON CONFLICT(station_id) DO UPDATE SET brand=excluded.brand,fetched_at=excluded.fetched_at""",
rows,
)
return len(rows)
def station_meta(station_ids):
"""Nom, commune, type de voie et enseigne connus pour ces stations."""
ids = [str(s) for s in station_ids if s]
if not ids:
return {}
marks = ",".join("?" * len(ids))
with connect() as db:
rows = db.execute(f"SELECT id, name, city, road FROM stations WHERE id IN ({marks})", ids).fetchall()
brands = db.execute(
f"SELECT station_id, brand FROM station_brand WHERE station_id IN ({marks})", ids
).fetchall()
out = {
station_id: dict(name="", city="", road="", brand=None)
for station_id in {row["id"] for row in rows} | {row["station_id"] for row in brands}
}
for row in rows:
out[row["id"]].update(name=row["name"], city=row["city"], road=row["road"])
for row in brands:
out[row["station_id"]]["brand"] = row["brand"]
return out
def history(lat, lon, radius, fuel, now=None):
now = now or datetime.now(timezone.utc)
today = now.astimezone(PARIS).date()
with connect() as db:
rows = db.execute(
"""SELECT * FROM observations WHERE fuel=? AND day>=? AND day<=?
ORDER BY day,station_id""",
(fuel, (today - timedelta(days=29)).isoformat(), today.isoformat()),
).fetchall()
days = {}
for row in rows:
if distance_km(lat, lon, row["lat"], row["lon"]) > radius:
continue
observed = datetime.fromisoformat(row["collected_at"])
if not fresh_price(row["source_updated"], observed):
continue
days.setdefault(row["day"], {})[row["station_id"]] = row["price"]
out = dict(
trend="unknown",
confidence="insufficient",
delta_per_liter=None,
matched_stations=0,
days=len(days),
series=[],
average_series=[],
stations_series=[],
summary="Historique insuffisant : au moins 7 jours observés couvrant une semaine sont nécessaires.",
)
if not days:
return out
# Moyenne brute des prix réellement enregistrés chaque jour (toutes stations confondues).
out["average_series"] = [
dict(day=day, average=round(statistics.mean(values.values()), 3), count=len(values))
for day, values in sorted(days.items())
]
# Série par station : uniquement les jours où cette station a réellement été observée.
per_station = {}
for day, values in sorted(days.items()):
for station_id, price in values.items():
per_station.setdefault(station_id, []).append(dict(day=day, price=round(price, 3)))
meta = station_meta(per_station.keys())
out["stations_series"] = [
dict(
station_id=station_id,
name=(meta.get(station_id, {}).get("name") or f"Station {station_id}"),
city=meta.get(station_id, {}).get("city") or "",
road=meta.get(station_id, {}).get("road") or "",
brand=meta.get(station_id, {}).get("brand"),
series=points,
lowest=min(p["price"] for p in points),
highest=max(p["price"] for p in points),
delta=round(points[-1]["price"] - points[0]["price"], 3),
)
for station_id, points in sorted(per_station.items(), key=lambda item: item[1][-1]["price"])
]
# Graphe sur panel constant : aucun effet dû à l'apparition d'une station.
common = set.intersection(*(set(values) for values in days.values()))
if common:
out["series"] = [
dict(day=day, median=round(statistics.median(values[s] for s in common), 3), count=len(common))
for day, values in days.items()
]
recent = {d: v for d, v in days.items() if d >= (today - timedelta(days=10)).isoformat()}
if len(recent) < 7:
return out
first, last = min(recent), max(recent)
if (today - datetime.fromisoformat(last).date()).days > 1 or (
datetime.fromisoformat(last) - datetime.fromisoformat(first)
).days < 7:
return out
common = set.intersection(*(set(values) for values in recent.values()))
if not common:
out["summary"] = "Panel de stations constant insuffisant pour comparer les prix."
return out
delta = statistics.median(recent[last][s] - recent[first][s] for s in common)
trend = "up" if delta >= 0.02 else "down" if delta <= -0.02 else "flat"
label = {"up": "hausse", "down": "baisse", "flat": "stabilité"}[trend]
out.update(
trend=trend,
confidence="limited" if len(common) < 3 else "observed",
delta_per_liter=round(delta, 3),
matched_stations=len(common),
start=first,
end=last,
summary=f"{label.capitalize()} observée : {delta:+.3f} €/L du {first} au {last}, "
f"sur les mêmes {len(common)} stations. Ce n’est pas une prévision.",
)
return out
DB_PATH = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) / "fuel.sqlite3"
FUELS = ["Gazole", "SP95", "SP98", "E10", "E85", "GPLc"]
@contextmanager
def connect():
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
db = sqlite3.connect(DB_PATH, timeout=20)
db.row_factory = sqlite3.Row
db.execute("PRAGMA foreign_keys=ON")
try:
with db:
db.executescript("""
CREATE TABLE IF NOT EXISTS vehicles (id INTEGER PRIMARY KEY, data TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS favorites (id INTEGER PRIMARY KEY, data TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS observations (
station_id TEXT NOT NULL, fuel TEXT NOT NULL, day TEXT NOT NULL,
price REAL NOT NULL, source_updated TEXT NOT NULL,
collected_at TEXT NOT NULL, lat REAL NOT NULL, lon REAL NOT NULL,
PRIMARY KEY(station_id, fuel, day));
CREATE TABLE IF NOT EXISTS collections (
id INTEGER PRIMARY KEY, started_at TEXT NOT NULL,
finished_at TEXT, status TEXT NOT NULL, count INTEGER DEFAULT 0,
detail TEXT NOT NULL DEFAULT '');
CREATE TABLE IF NOT EXISTS market_daily (
day TEXT PRIMARY KEY, payload TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS stations (
id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', city TEXT NOT NULL DEFAULT '',
road TEXT NOT NULL DEFAULT '', lat REAL, lon REAL, seen_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS station_brand (
station_id TEXT PRIMARY KEY, brand TEXT, fetched_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS upstream_series (
series TEXT NOT NULL, day TEXT NOT NULL, value REAL NOT NULL, unit TEXT NOT NULL,
source TEXT NOT NULL, fetched_at TEXT NOT NULL, PRIMARY KEY(series, day));
CREATE TABLE IF NOT EXISTS chokepoint_daily (
chokepoint TEXT NOT NULL, day TEXT NOT NULL, transit_tankers INTEGER,
transit_total INTEGER, capacity_tankers REAL, capacity_total REAL,
source TEXT NOT NULL, fetched_at TEXT NOT NULL, PRIMARY KEY(chokepoint, day));
CREATE TABLE IF NOT EXISTS upstream_runs (
day TEXT PRIMARY KEY, status TEXT NOT NULL, series INTEGER NOT NULL DEFAULT 0,
chokepoints INTEGER NOT NULL DEFAULT 0, detail TEXT NOT NULL DEFAULT '',
finished_at TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS observations_day ON observations(day);
CREATE INDEX IF NOT EXISTS observations_station ON observations(station_id);
""")
yield db
finally:
db.close()
def number(value, name, minimum, maximum):
try:
if isinstance(value, bool):
raise ValueError
out = float(value)
if not math.isfinite(out) or not minimum <= out <= maximum:
raise ValueError
return out
except (TypeError, ValueError):
raise ValueError(f"{name} : valeur attendue entre {minimum} et {maximum}.") from None
def table_name(kind):
if kind not in ("vehicles", "favorites"):
raise ValueError("Type inconnu")
return kind
def list_entities(kind):
with connect() as db:
return [
dict(id=row["id"], **json.loads(row["data"]))
for row in db.execute(f"SELECT id,data FROM {table_name(kind)} ORDER BY id")
]
def get_entity(kind, entity_id):
with connect() as db:
row = db.execute(f"SELECT data FROM {table_name(kind)} WHERE id=?", (entity_id,)).fetchone()
if row is None:
raise LookupError("Élément introuvable")
return dict(id=int(entity_id), **json.loads(row["data"]))
def save_entity(kind, data, entity_id=None):
table_name(kind)
if not isinstance(data, dict):
raise ValueError("Objet JSON attendu")
name = str(data.get("name", "")).strip()
if not 1 <= len(name) <= 80:
raise ValueError("Nom requis, 80 caractères maximum")
clean = {"name": name}
if kind == "favorites":
clean.update(
lat=number(data.get("lat"), "Latitude", -90, 90),
lon=number(data.get("lon"), "Longitude", -180, 180),
radius_km=number(data.get("radius_km"), "Rayon", 1, 80),
)
else:
fuel, usage = data.get("fuel"), data.get("usage")
if fuel not in FUELS or usage not in ("regular", "occasional"):
raise ValueError("Carburant ou usage invalide")
clean.update(
fuel=fuel,
usage=usage,
consumption=number(data.get("consumption"), "Consommation", 0.1, 60),
min_range_km=number(data.get("min_range_km"), "Marge km", 0, 1500),
monthly_km=number(
data.get("monthly_km", 0), "Km mensuels", 1 if usage == "regular" else 0, 30000
),
tank_liters=None
if data.get("tank_liters") in (None, "")
else number(data["tank_liters"], "Réservoir", 1, 300),
)
with connect() as db:
if entity_id is None:
if db.execute(f"SELECT count(*) FROM {kind}").fetchone()[0] >= 100:
raise ValueError("Limite de 100 éléments atteinte")
entity_id = db.execute(
f"INSERT INTO {kind}(data) VALUES(?)", (json.dumps(clean, ensure_ascii=False),)
).lastrowid
elif (
db.execute(
f"UPDATE {kind} SET data=? WHERE id=?", (json.dumps(clean, ensure_ascii=False), entity_id)
).rowcount
== 0
):
raise LookupError("Élément introuvable")
return dict(id=entity_id, **clean)
def delete_entity(kind, entity_id):
with connect() as db:
if not db.execute(f"DELETE FROM {table_name(kind)} WHERE id=?", (entity_id,)).rowcount:
raise LookupError("Élément introuvable")