Afficher les enseignes, ajouter un fournisseur pétrole en secours et tracer les prix
Enseignes via OpenStreetMap/Nominatim (cache 30 jours, correspondance a 120 m, aucune enseigne inventee). Cotation du petrole en chaine stooq puis page publique, conversion euro avec la BCE, jamais de fausse stabilite. Graphes moyenne journaliere des releves et une courbe par station. Noms de stations et type de voie conserves pour l affichage.
This commit is contained in:
95
storage.py
95
storage.py
@@ -52,9 +52,71 @@ def record_observations(rows, now=None):
|
||||
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 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()
|
||||
@@ -79,10 +141,37 @@ def history(lat, lon, radius, fuel, now=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:
|
||||
@@ -144,7 +233,13 @@ def connect():
|
||||
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 INDEX IF NOT EXISTS observations_day ON observations(day);
|
||||
CREATE INDEX IF NOT EXISTS observations_station ON observations(station_id);
|
||||
""")
|
||||
yield db
|
||||
finally:
|
||||
|
||||
Reference in New Issue
Block a user