Files
Fuel-Advisor/storage.py
root c0e930df76 Distances routieres reelles, navigation, synthese amont lisible et file Ollama supervisee
Le rayon porte desormais sur la distance routiere (prefiltre a vol d oiseau, puis itineraire reel via OSRM par defaut et Google Routes API si une cle est fournie). Chaque station affiche distance en voiture, duree, prix, enseigne et deux liens de navigation Google Maps et Waze sur ses coordonnees exactes ; distance et duree sont mises en cache pour le futur cout de detour. La section amont devient une synthese comprehensible (pression, confiance, facteurs en langage courant, paragraphe En clair) avec les donnees techniques repliees. La file Ollama est prefiltree de facon deterministe, mesuree et exposee dans la supervision (articles en attente, age du plus ancien, analyses sur 24 h, duree moyenne, echecs par modele).
2026-09-12 23:00:07 +02:00

956 lines
39 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:
rows_with_meta = [(*value, value[3], value[4]) for value in values.values()]
db.executemany(
"""INSERT INTO observations(station_id,fuel,day,price,source_updated,collected_at,lat,lon,
published_at,fetched_at) 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,published_at=excluded.published_at,
fetched_at=excluded.fetched_at""",
rows_with_meta,
)
# 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(),
str(row.get("observed_at") or row["day"]),
row.get("published_at"),
)
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(series,day,value,unit,source,fetched_at,observed_at,published_at)
VALUES(?,?,?,?,?,?,?,?)
ON CONFLICT(series,day) DO UPDATE SET value=excluded.value,unit=excluded.unit,
source=excluded.source,fetched_at=excluded.fetched_at,
observed_at=excluded.observed_at,published_at=excluded.published_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)
pairs = entries.items() if isinstance(entries, dict) else (entries or [])
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 pairs
if entry and 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 _ensure_columns(db, table, columns):
"""Ajout de colonnes idempotent (aucune perte de données existante)."""
existing = {row["name"] for row in db.execute(f"PRAGMA table_info({table})")}
for name, ddl in columns.items():
if name not in existing:
db.execute(f"ALTER TABLE {table} ADD COLUMN {name} {ddl}")
def record_price_events(rows, now=None, source="prix-carburants.gouv.fr (flux instantané)"):
"""Journalise un événement prix **uniquement** si le prix ou l'horodatage déclaré a changé.
``declared_at`` est l'horodatage publié par la station, ``observed_at`` celui de la collecte :
le modèle futur ne doit jamais confondre les deux avec la date de téléchargement.
"""
now = now or datetime.now(timezone.utc)
observed_at = now.isoformat()
candidates = []
for row in rows:
for fuel, price in row["prices"].items():
if fuel in FUELS and math.isfinite(price) and 0 < price < 20:
candidates.append((str(row["id"]), fuel, price, str(row["updates"].get(fuel, ""))))
if not candidates:
return 0
identifiers = {(station_id, fuel) for station_id, fuel, _, _ in candidates}
with connect() as db:
placeholders = " OR ".join(["(station_id=? AND fuel=?)"] * len(identifiers))
args = [value for pair in identifiers for value in pair]
previous = {}
for row in db.execute(
f"""SELECT station_id, fuel, price, declared_at FROM price_events WHERE {placeholders}
AND observed_at = (SELECT max(observed_at) FROM price_events p2
WHERE p2.station_id = price_events.station_id
AND p2.fuel = price_events.fuel)""",
args,
):
previous[(row["station_id"], row["fuel"])] = (row["price"], row["declared_at"])
inserted = []
for station_id, fuel, price, declared_at in candidates:
last_price, last_declared = previous.get((station_id, fuel), (None, None))
changed = (
last_price is None
or round(last_price, 3) != round(price, 3)
or (declared_at and declared_at != last_declared)
)
if not changed:
continue
inserted.append(
(station_id, fuel, observed_at, price, declared_at, last_price, observed_at, source)
)
if not inserted:
return 0
with connect() as db:
db.executemany(
"""INSERT INTO price_events VALUES(?,?,?,?,?,?,?,?)
ON CONFLICT(station_id,fuel,observed_at) DO UPDATE SET price=excluded.price,
declared_at=excluded.declared_at,previous_price=excluded.previous_price,
fetched_at=excluded.fetched_at,source=excluded.source""",
inserted,
)
return len(inserted)
def price_events(station_id=None, days=30):
query = "SELECT * FROM price_events WHERE observed_at>=?"
args = [(datetime.now(timezone.utc) - timedelta(days=days)).isoformat()]
if station_id:
query += " AND station_id=?"
args.append(str(station_id))
with connect() as db:
rows = db.execute(query + " ORDER BY observed_at DESC", args).fetchall()
return [dict(row) for row in rows]
def route_key(origin, target, precision=4):
"""Clé de cache : positions arrondies (la route ne change pas au mètre près)."""
parts = [round(float(value), precision) for value in (*origin, *target)]
return "|".join(f"{part:.{precision}f}" for part in parts)
def route_lookup(keys, max_age_days=90, now=None):
"""Routes déjà calculées et encore valables (les routes changent lentement)."""
keys = list(keys)
if not keys:
return {}
now = now or datetime.now(timezone.utc)
floor = (now - timedelta(days=max_age_days)).isoformat()
out = {}
with connect() as db:
for chunk_start in range(0, len(keys), 400):
chunk = keys[chunk_start : chunk_start + 400]
placeholders = ",".join("?" * len(chunk))
for row in db.execute(
f"SELECT * FROM route_cache WHERE key IN ({placeholders}) AND computed_at>=?", (*chunk, floor)
):
out[row["key"]] = dict(row)
return out
def route_save(rows, now=None):
"""Enregistre les distances routières calculées (base du futur coût de détour)."""
now = now or datetime.now(timezone.utc)
values = [
(
row["key"],
row["origin_lat"],
row["origin_lon"],
row["target_lat"],
row["target_lon"],
row["distance_m"],
row.get("duration_s"),
row["provider"],
now.isoformat(),
)
for row in rows
if row.get("distance_m") and math.isfinite(row["distance_m"])
]
if not values:
return 0
with connect() as db:
db.executemany(
"""INSERT INTO route_cache VALUES(?,?,?,?,?,?,?,?,?)
ON CONFLICT(key) DO UPDATE SET distance_m=excluded.distance_m,
duration_s=excluded.duration_s,provider=excluded.provider,computed_at=excluded.computed_at""",
values,
)
return len(values)
def record_llm_run(url_hash, topic, model, duration_s, ok=True, detail="", now=None):
stamp = (now or datetime.now(timezone.utc)).isoformat()
with connect() as db:
db.execute(
"REPLACE INTO llm_runs(url_hash,topic,model,duration_s,ok,detail,at) VALUES(?,?,?,?,?,?,?)",
(
str(url_hash),
str(topic),
str(model),
float(duration_s),
1 if ok else 0,
str(detail)[:200],
stamp,
),
)
def llm_queue(now=None):
"""État réel de la file d'analyse : retard, débit et durée, jamais masqué."""
now = now or datetime.now(timezone.utc)
day_ago = (now - timedelta(days=1)).isoformat()
with connect() as db:
pending = db.execute(
"SELECT count(*) n, min(fetched_at) oldest FROM news_articles "
"WHERE analysed_at IS NULL AND skip_reason IS NULL"
).fetchone()
skipped = db.execute("SELECT count(*) n FROM news_articles WHERE skip_reason IS NOT NULL").fetchone()
total = db.execute("SELECT count(*) n FROM news_articles").fetchone()
analysed = db.execute(
"SELECT count(*) n FROM news_articles WHERE analysed_at>=?", (day_ago,)
).fetchone()
durations = db.execute(
"SELECT count(*) n, avg(duration_s) avg_s, max(duration_s) max_s, sum(ok = 0) fails "
"FROM llm_runs WHERE at>=?",
(day_ago,),
).fetchone()
by_model = [
dict(row)
for row in db.execute(
"SELECT model, count(*) n, avg(duration_s) avg_s, sum(ok = 0) fails FROM llm_runs "
"WHERE at>=? GROUP BY model ORDER BY n DESC",
(day_ago,),
)
]
oldest = pending["oldest"]
age_hours = None
if oldest:
try:
age_hours = round((now - datetime.fromisoformat(oldest)).total_seconds() / 3600, 1)
except ValueError:
age_hours = None
return dict(
pending=pending["n"],
oldest_pending_at=oldest,
oldest_pending_age_hours=age_hours,
skipped=skipped["n"],
total=total["n"],
analysed_24h=analysed["n"],
analysed_24h_avg_seconds=round(durations["avg_s"], 1) if durations["avg_s"] else None,
analysed_24h_max_seconds=round(durations["max_s"], 1) if durations["max_s"] else None,
analysed_24h_failures=durations["fails"] or 0,
by_model=by_model,
)
def job_get(name):
with connect() as db:
row = db.execute("SELECT * FROM jobs WHERE name=?", (name,)).fetchone()
return dict(row) if row else None
def jobs_list():
with connect() as db:
return [dict(row) for row in db.execute("SELECT * FROM jobs ORDER BY name")]
def job_record(
name,
source,
frequency,
cadence_seconds,
status,
detail="",
stored=0,
last_observation_at=None,
next_run_at=None,
now=None,
):
"""Met à jour la supervision d'un collecteur (jamais masquée, même en échec)."""
now = now or datetime.now(timezone.utc)
stamp = now.isoformat()
with connect() as db:
current = db.execute("SELECT * FROM jobs WHERE name=?", (name,)).fetchone()
success = (
stamp if status in ("ok", "unchanged") else (current["last_success_at"] if current else None)
)
failures = (current["fail_count"] if current else 0) + (1 if status == "error" else 0)
db.execute(
"""REPLACE INTO jobs VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
name,
source,
frequency,
int(cadence_seconds),
stamp,
success,
next_run_at or (current["next_run_at"] if current else None),
status,
detail[:300],
stored,
(current["run_count"] if current else 0) + 1,
failures,
last_observation_at or (current["last_observation_at"] if current else None),
),
)
return job_get(name)
def save_articles(articles, topic, now=None):
"""Enregistre les articles rencontrés ; renvoie ceux jamais analysés (nouveaux)."""
now = now or datetime.now(timezone.utc)
stamp = now.isoformat()
fresh = []
with connect() as db:
for article in articles:
digest = article["hash"]
row = db.execute("SELECT analysed_at FROM news_articles WHERE url_hash=?", (digest,)).fetchone()
if row is None:
db.execute(
"REPLACE INTO news_articles(url_hash,url,title,source,published_at,observed_at,"
"fetched_at,topic,analysed_at,skip_reason) VALUES(?,?,?,?,?,?,?,?,NULL,NULL)",
(
digest,
article["url"],
article["title"][:300],
article.get("source", "")[:80],
article.get("published_at"),
article.get("observed_at"),
stamp,
topic,
),
)
fresh.append(article)
elif row["analysed_at"] is None and article.get("retry", False):
fresh.append(article)
return fresh
def mark_skipped(hashes, reason, now=None):
"""Article écarté par le préfiltrage : conservé, daté, et jamais réanalysé."""
stamp = (now or datetime.now(timezone.utc)).isoformat()
if not hashes:
return 0
with connect() as db:
for digest in hashes:
db.execute(
"UPDATE news_articles SET analysed_at=?, skip_reason=? WHERE url_hash=?",
(stamp, str(reason)[:120], digest),
)
return len(hashes)
def pending_articles(limit=50, topic=None):
"""Articles en attente d'analyse, du plus ancien au plus récent."""
query = "SELECT * FROM news_articles WHERE analysed_at IS NULL AND skip_reason IS NULL"
args = []
if topic:
query += " AND topic=?"
args.append(topic)
with connect() as db:
rows = db.execute(query + " ORDER BY fetched_at LIMIT ?", (*args, limit)).fetchall()
return [dict(row) for row in rows]
def mark_analysed(hashes, now=None):
stamp = (now or datetime.now(timezone.utc)).isoformat()
if not hashes:
return 0
with connect() as db:
for digest in hashes:
db.execute("UPDATE news_articles SET analysed_at=? WHERE url_hash=?", (stamp, digest))
return len(hashes)
def save_news_event(event, now=None):
stamp = (now or datetime.now(timezone.utc)).isoformat()
with connect() as db:
db.execute(
"""INSERT INTO news_events(url_hash,topic,event_type,direction,magnitude,fuels,zone,horizon_days,
confidence,valid_from,valid_until,observed_at,published_at,fetched_at,source_url,extracted_by)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(url_hash,topic,event_type) DO UPDATE SET direction=excluded.direction,
magnitude=excluded.magnitude,fuels=excluded.fuels,zone=excluded.zone,
horizon_days=excluded.horizon_days,confidence=excluded.confidence,
valid_from=excluded.valid_from,valid_until=excluded.valid_until,fetched_at=excluded.fetched_at""",
(
event["url_hash"],
event["topic"],
event["event_type"],
event["direction"],
event.get("magnitude", ""),
",".join(event.get("fuels") or []),
event.get("zone", ""),
event.get("horizon_days"),
event.get("confidence"),
event.get("valid_from"),
event.get("valid_until"),
event.get("observed_at"),
event.get("published_at"),
stamp,
event["source_url"],
event.get("extracted_by", ""),
),
)
def news_events(days=30):
with connect() as db:
rows = db.execute(
"""SELECT * FROM news_events WHERE fetched_at>=? AND (valid_until IS NULL OR valid_until>=?)
ORDER BY confidence DESC, fetched_at DESC LIMIT 60""",
(
(datetime.now(timezone.utc) - timedelta(days=days)).isoformat(),
datetime.now(timezone.utc).date().isoformat(),
),
).fetchall()
return [dict(row) for row in rows]
def save_promotions(promotions, now=None):
stamp = (now or datetime.now(timezone.utc)).isoformat()
saved = 0
with connect() as db:
for promotion in promotions:
db.execute(
"""INSERT INTO promotions(brand,scope,stations,fuels,nature,discount_per_liter,valid_from,
valid_until,observed_at,published_at,fetched_at,source_url,confidence,extracted_by,raw_excerpt)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(source_url,brand,nature,valid_from) DO UPDATE SET
discount_per_liter=excluded.discount_per_liter,valid_until=excluded.valid_until,
fetched_at=excluded.fetched_at,confidence=excluded.confidence,raw_excerpt=excluded.raw_excerpt""",
(
promotion["brand"],
promotion.get("scope", ""),
promotion.get("stations", ""),
",".join(promotion.get("fuels") or []),
promotion["nature"],
promotion.get("discount_per_liter"),
promotion.get("valid_from"),
promotion.get("valid_until"),
promotion.get("observed_at"),
promotion.get("published_at"),
stamp,
promotion["source_url"],
promotion.get("confidence"),
promotion.get("extracted_by", ""),
promotion.get("raw_excerpt", "")[:500],
),
)
saved += 1
return saved
def promotions(days=30, today=None):
today = today or datetime.now(timezone.utc).date()
with connect() as db:
rows = db.execute(
"""SELECT * FROM promotions WHERE (valid_until IS NULL OR valid_until>=?)
AND fetched_at>=? ORDER BY valid_from""",
(today.isoformat(), (today - timedelta(days=days)).isoformat()),
).fetchall()
return [dict(row) for row in rows]
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 TABLE IF NOT EXISTS jobs (
name TEXT PRIMARY KEY, source TEXT NOT NULL DEFAULT '', frequency TEXT NOT NULL DEFAULT '',
cadence_seconds INTEGER NOT NULL DEFAULT 0, last_run_at TEXT, last_success_at TEXT,
next_run_at TEXT, status TEXT NOT NULL DEFAULT 'never', detail TEXT NOT NULL DEFAULT '',
stored INTEGER NOT NULL DEFAULT 0, run_count INTEGER NOT NULL DEFAULT 0,
fail_count INTEGER NOT NULL DEFAULT 0, last_observation_at TEXT);
CREATE TABLE IF NOT EXISTS price_events (
station_id TEXT NOT NULL, fuel TEXT NOT NULL, observed_at TEXT NOT NULL,
price REAL NOT NULL, declared_at TEXT NOT NULL DEFAULT '', previous_price REAL,
fetched_at TEXT NOT NULL, source TEXT NOT NULL DEFAULT '',
PRIMARY KEY(station_id, fuel, observed_at));
CREATE TABLE IF NOT EXISTS news_articles (
url_hash TEXT PRIMARY KEY, url TEXT NOT NULL, title TEXT NOT NULL, source TEXT NOT NULL DEFAULT '',
published_at TEXT, observed_at TEXT, fetched_at TEXT NOT NULL,
topic TEXT NOT NULL DEFAULT '', analysed_at TEXT);
CREATE TABLE IF NOT EXISTS news_events (
id INTEGER PRIMARY KEY, url_hash TEXT NOT NULL, topic TEXT NOT NULL, event_type TEXT NOT NULL,
direction TEXT NOT NULL, magnitude TEXT NOT NULL DEFAULT '', fuels TEXT NOT NULL DEFAULT '',
zone TEXT NOT NULL DEFAULT '', horizon_days INTEGER, confidence REAL,
valid_from TEXT, valid_until TEXT, observed_at TEXT, published_at TEXT, fetched_at TEXT NOT NULL,
source_url TEXT NOT NULL, extracted_by TEXT NOT NULL DEFAULT '',
UNIQUE(url_hash, topic, event_type));
CREATE TABLE IF NOT EXISTS route_cache (
key TEXT PRIMARY KEY, origin_lat REAL NOT NULL, origin_lon REAL NOT NULL,
target_lat REAL NOT NULL, target_lon REAL NOT NULL, distance_m REAL NOT NULL,
duration_s REAL, provider TEXT NOT NULL, computed_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS llm_runs (
id INTEGER PRIMARY KEY, url_hash TEXT NOT NULL, topic TEXT NOT NULL DEFAULT '',
model TEXT NOT NULL, duration_s REAL NOT NULL, ok INTEGER NOT NULL DEFAULT 1,
detail TEXT NOT NULL DEFAULT '', at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS promotions (
id INTEGER PRIMARY KEY, brand TEXT NOT NULL, scope TEXT NOT NULL DEFAULT '',
stations TEXT NOT NULL DEFAULT '', fuels TEXT NOT NULL DEFAULT '',
nature TEXT NOT NULL, discount_per_liter REAL, valid_from TEXT, valid_until TEXT,
observed_at TEXT, published_at TEXT, fetched_at TEXT NOT NULL,
source_url TEXT NOT NULL, confidence REAL, extracted_by TEXT NOT NULL DEFAULT '',
raw_excerpt TEXT NOT NULL DEFAULT '', UNIQUE(source_url, brand, nature, valid_from));
CREATE INDEX IF NOT EXISTS observations_day ON observations(day);
CREATE INDEX IF NOT EXISTS observations_station ON observations(station_id);
""")
_ensure_columns(db, "upstream_series", {"observed_at": "TEXT", "published_at": "TEXT"})
_ensure_columns(db, "observations", {"published_at": "TEXT", "fetched_at": "TEXT"})
_ensure_columns(db, "news_articles", {"skip_reason": "TEXT"})
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")