Ordonnanceur multi-frequences, supervision, promotions et metadonnees temporelles
Chaque source a sa cadence et sa fenetre (prix locaux horaires 24/7, BCE jours ouvres apres 16h15, bulletin UE le jeudi, DGEC mensuel avec detection de nouvelle periode, PortWatch quotidien avec fenetre glissante pour les revisions, actualites toutes les 2 heures, promotions 3 fois par jour). Supervision persistante (table jobs) exposee par /api/jobs et une fenetre dediee. Evenements prix uniquement en cas de changement de prix ou d horodatage declare, actualisation forcee du flux local au-dela de 15 minutes lors d un conseil. Extraction Ollama (mistral-small3.2:24b) des actualites geopolitiques et des operations commerciales, sans jamais decider du conseil, avec observed_at, published_at, fetched_at, valid_from et valid_until distincts.
This commit is contained in:
317
storage.py
317
storage.py
@@ -45,12 +45,15 @@ def record_observations(rows, now=None):
|
||||
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 VALUES(?,?,?,?,?,?,?,?)
|
||||
"""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""",
|
||||
list(values.values()),
|
||||
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 = {
|
||||
@@ -121,7 +124,16 @@ 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(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"])
|
||||
]
|
||||
@@ -129,9 +141,11 @@ def save_upstream(series, rows, unit, source, now=None):
|
||||
return 0
|
||||
with connect() as db:
|
||||
db.executemany(
|
||||
"""INSERT INTO upstream_series VALUES(?,?,?,?,?,?)
|
||||
"""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""",
|
||||
source=excluded.source,fetched_at=excluded.fetched_at,
|
||||
observed_at=excluded.observed_at,published_at=excluded.published_at""",
|
||||
values,
|
||||
)
|
||||
return len(values)
|
||||
@@ -140,6 +154,7 @@ def save_upstream(series, rows, unit, source, now=None):
|
||||
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,
|
||||
@@ -151,8 +166,8 @@ def save_chokepoints(entries, source, now=None):
|
||||
str(source),
|
||||
now.isoformat(),
|
||||
)
|
||||
for name, entry in (entries or {}).items()
|
||||
if entry.get("day")
|
||||
for name, entry in pairs
|
||||
if entry and entry.get("day")
|
||||
]
|
||||
if not values:
|
||||
return 0
|
||||
@@ -230,6 +245,261 @@ def chokepoint_daily(days=60):
|
||||
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 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 VALUES(?,?,?,?,?,?,?,?,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_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)
|
||||
@@ -403,9 +673,40 @@ def connect():
|
||||
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 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"})
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
Reference in New Issue
Block a user