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.
292 lines
12 KiB
Python
292 lines
12 KiB
Python
"""Collecte quotidienne : prix locaux des favoris + sources amont officielles.
|
||
|
||
Deux responsabilités séparées :
|
||
- ``collect`` : prix locaux (nécessite au moins un favori) ;
|
||
- ``collect_upstream`` : séries amont officielles (DGEC, bulletin UE, détroits IMF),
|
||
indépendantes des favoris, donc collectées même sans lieu suivi.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import fcntl
|
||
import json
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
import storage
|
||
import upstream
|
||
|
||
DGEC_SOURCE = "DGEC – ministère de la Transition écologique (mensuel)"
|
||
EU_SOURCE = "Commission européenne – Weekly Oil Bulletin (hebdomadaire)"
|
||
PORTWATCH_SOURCE = "IMF PortWatch (quotidien, publication différée)"
|
||
MARKET_SOURCE = "Cotation de marché (quotidienne, voir marché amont)"
|
||
|
||
|
||
def status():
|
||
with storage.connect() as db:
|
||
latest = db.execute("SELECT * FROM collections ORDER BY id DESC LIMIT 1").fetchone()
|
||
good = db.execute("SELECT * FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1").fetchone()
|
||
count = db.execute("SELECT count(*) FROM observations").fetchone()[0]
|
||
run = db.execute("SELECT * FROM upstream_runs ORDER BY day DESC LIMIT 1").fetchone()
|
||
return dict(
|
||
latest=dict(latest) if latest else None,
|
||
last_success=dict(good) if good else None,
|
||
observations=count,
|
||
upstream_run=dict(run) if run else None,
|
||
upstream=storage.latest_upstream(),
|
||
)
|
||
|
||
|
||
def _source_dgec():
|
||
"""Cours du Brent, marge brute de raffinage, prix HTT/TTC français."""
|
||
urls = upstream.dgec_urls()
|
||
out = []
|
||
brent = upstream.parse_dgec_brent(upstream.fetch_bytes(urls["brent"], 90))
|
||
out.append(
|
||
dict(
|
||
series="dgec_brent_usd",
|
||
unit="USD/baril",
|
||
source=DGEC_SOURCE,
|
||
rows=[dict(day=row["day"], value=row["value"]) for row in brent],
|
||
)
|
||
)
|
||
margin = upstream.parse_dgec_margin(upstream.fetch_bytes(urls["margin"], 90))
|
||
out.append(
|
||
dict(
|
||
series="dgec_margin_usd_per_bbl",
|
||
unit="USD/baril",
|
||
source=DGEC_SOURCE,
|
||
rows=[dict(day=row["day"], value=row["usd_per_bbl"]) for row in margin],
|
||
)
|
||
)
|
||
out.append(
|
||
dict(
|
||
series="dgec_margin_eur_per_tonne",
|
||
unit="EUR/tonne",
|
||
source=DGEC_SOURCE,
|
||
rows=[dict(day=row["day"], value=row["eur_per_tonne"]) for row in margin],
|
||
)
|
||
)
|
||
prices = upstream.parse_dgec_prices(upstream.fetch_bytes(urls["prices"], 90))
|
||
for fuel in storage.FUELS:
|
||
htt = [dict(day=row["day"], value=row["htt"][fuel]) for row in prices if fuel in row["htt"]]
|
||
ttc = [dict(day=row["day"], value=row["ttc"][fuel]) for row in prices if fuel in row["ttc"]]
|
||
if htt:
|
||
out.append(
|
||
dict(series=f"fr_htt_{fuel}", unit="EUR/L", source=f"{DGEC_SOURCE} – hors taxes", rows=htt)
|
||
)
|
||
if ttc:
|
||
out.append(dict(series=f"fr_ttc_{fuel}", unit="EUR/L", source=f"{DGEC_SOURCE} – TTC", rows=ttc))
|
||
return out
|
||
|
||
|
||
def _source_eu_bulletin():
|
||
"""Prix hebdomadaires français du bulletin pétrolier européen (TTC et hors taxes)."""
|
||
url = upstream.eu_bulletin_url()
|
||
raw = upstream.fetch_bytes(url, 200)
|
||
with_ttc = upstream.parse_eu_bulletin(raw, "FR", "Prices with taxes")
|
||
without = upstream.parse_eu_bulletin(raw, "FR", "Prices wo taxes")
|
||
out = []
|
||
for product in ("diesel", "euro95", "euro98"):
|
||
ttc = [
|
||
dict(day=row["day"], value=row["prices"][product]) for row in with_ttc if product in row["prices"]
|
||
]
|
||
htt = [
|
||
dict(day=row["day"], value=row["prices"][product]) for row in without if product in row["prices"]
|
||
]
|
||
if ttc:
|
||
out.append(
|
||
dict(series=f"eu_fr_{product}_ttc", unit="EUR/L", source=f"{EU_SOURCE} – TTC", rows=ttc)
|
||
)
|
||
if htt:
|
||
out.append(
|
||
dict(
|
||
series=f"eu_fr_{product}_htt", unit="EUR/L", source=f"{EU_SOURCE} – hors taxes", rows=htt
|
||
)
|
||
)
|
||
return out
|
||
|
||
|
||
def _source_market_daily():
|
||
"""Cotation quotidienne du Brent + taux BCE, pour l'historique de long terme."""
|
||
import market
|
||
|
||
quote = market.fetch(force=True)
|
||
if quote.get("trend") == "unknown" and quote.get("price_usd") is None:
|
||
raise ValueError(quote.get("summary", "cotation indisponible"))
|
||
out = []
|
||
if quote.get("price_usd") and quote.get("date"):
|
||
out.append(
|
||
dict(
|
||
series="brent_usd_daily",
|
||
unit="USD/baril",
|
||
source=quote.get("source") or MARKET_SOURCE,
|
||
rows=[dict(day=quote["date"], value=quote["price_usd"])],
|
||
)
|
||
)
|
||
if quote.get("price_eur") and quote.get("date"):
|
||
out.append(
|
||
dict(
|
||
series="brent_eur_daily",
|
||
unit="EUR/baril",
|
||
source=quote.get("source") or MARKET_SOURCE,
|
||
rows=[dict(day=quote["date"], value=quote["price_eur"])],
|
||
)
|
||
)
|
||
rate = market.ecb_usd_per_eur()
|
||
if rate:
|
||
out.append(
|
||
dict(
|
||
series="usd_per_eur",
|
||
unit="USD/EUR",
|
||
source="BCE (quotidien)",
|
||
rows=[dict(day=datetime.now(timezone.utc).date().isoformat(), value=rate)],
|
||
)
|
||
)
|
||
return out
|
||
|
||
|
||
def _source_chokepoints():
|
||
entries, warning = upstream.fetch_chokepoints()
|
||
if not entries:
|
||
raise ValueError(warning or "aucun détroit exploitable")
|
||
return entries
|
||
|
||
|
||
UPSTREAM_SOURCES = {
|
||
"dgec": _source_dgec,
|
||
"eu_bulletin": _source_eu_bulletin,
|
||
"market_daily": _source_market_daily,
|
||
"chokepoints": _source_chokepoints,
|
||
}
|
||
|
||
|
||
def collect_upstream(force=False, sources=None):
|
||
"""Collecte les séries amont une fois par jour civil (heure de Paris)."""
|
||
sources = UPSTREAM_SOURCES if sources is None else sources
|
||
now = datetime.now(timezone.utc)
|
||
day = now.astimezone(storage.PARIS).date().isoformat()
|
||
with storage.connect() as db:
|
||
previous = db.execute("SELECT status FROM upstream_runs WHERE day=?", (day,)).fetchone()
|
||
if not force and previous and previous["status"] == "ok":
|
||
return dict(status="skipped", day=day, detail="déjà collecté aujourd’hui")
|
||
storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
with (storage.DB_PATH.parent / "upstream.lock").open("a") as lock:
|
||
try:
|
||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||
except BlockingIOError:
|
||
return dict(status="busy", day=day, detail="collecte amont déjà en cours")
|
||
stored, failures, chokepoints = 0, [], 0
|
||
for name, source in sources.items():
|
||
try:
|
||
payload = source()
|
||
if name == "chokepoints":
|
||
chokepoints = storage.save_chokepoints(payload, PORTWATCH_SOURCE, now)
|
||
continue
|
||
for block in payload:
|
||
stored += storage.save_upstream(
|
||
block["series"], block["rows"], block["unit"], block["source"], now
|
||
)
|
||
except Exception as exc:
|
||
failures.append(f"{name}: {type(exc).__name__} {str(exc)[:90]}")
|
||
outcome = "partial" if failures and stored else "error" if failures else "ok"
|
||
detail = " ; ".join(failures)[:400]
|
||
with storage.connect() as db:
|
||
db.execute(
|
||
"REPLACE INTO upstream_runs VALUES(?,?,?,?,?,?)",
|
||
(day, outcome, stored, chokepoints, detail, now.isoformat()),
|
||
)
|
||
return dict(status=outcome, day=day, series=stored, chokepoints=chokepoints, detail=detail)
|
||
|
||
|
||
def collect(load=None, force=False):
|
||
upstream_result = {"status": "not_run"}
|
||
try:
|
||
upstream_result = collect_upstream(force=force)
|
||
except Exception as exc: # ne doit jamais empêcher la collecte locale
|
||
upstream_result = {"status": "error", "detail": f"{type(exc).__name__}: {str(exc)[:120]}"}
|
||
if load is None:
|
||
import app
|
||
|
||
def load():
|
||
return app.load_fuel_data(force=True)
|
||
|
||
now = datetime.now(timezone.utc)
|
||
day = now.astimezone(storage.PARIS).date().isoformat()
|
||
storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
with (storage.DB_PATH.parent / "collection.lock").open("a") as lock:
|
||
try:
|
||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||
except BlockingIOError:
|
||
return {"status": "busy", "count": 0, "upstream": upstream_result}
|
||
favorites = storage.list_entities("favorites")
|
||
if not favorites:
|
||
return {"status": "no_favorites", "count": 0, "upstream": upstream_result}
|
||
with storage.connect() as db:
|
||
last = db.execute(
|
||
"SELECT finished_at FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1"
|
||
).fetchone()
|
||
if (
|
||
not force
|
||
and last
|
||
and datetime.fromisoformat(last[0]).astimezone(storage.PARIS).date().isoformat() == day
|
||
):
|
||
return {"status": "skipped", "count": 0, "upstream": upstream_result}
|
||
db.execute(
|
||
"UPDATE collections SET status='error', detail='Collecte précédente interrompue' "
|
||
"WHERE status='running'"
|
||
)
|
||
job = db.execute(
|
||
"INSERT INTO collections(started_at,status) VALUES(?,'running')", (now.isoformat(),)
|
||
).lastrowid
|
||
count, detail, outcome = 0, "", "ok"
|
||
try:
|
||
rows = load()
|
||
if not rows:
|
||
raise ValueError("Le flux national ne contient aucune station exploitable")
|
||
selected = [
|
||
row
|
||
for row in rows
|
||
if any(
|
||
storage.distance_km(f["lat"], f["lon"], row["lat"], row["lon"]) <= f["radius_km"]
|
||
for f in favorites
|
||
)
|
||
]
|
||
count = storage.record_observations(selected, now)
|
||
storage.sync_station_names(rows, now)
|
||
if not selected:
|
||
detail = "Aucune station dans les favoris actuels"
|
||
except Exception as exc:
|
||
outcome, detail = "error", f"{type(exc).__name__}: {str(exc)[:250]}"
|
||
with storage.connect() as db:
|
||
db.execute(
|
||
"UPDATE collections SET finished_at=?, status=?, count=?, detail=? WHERE id=?",
|
||
(datetime.now(timezone.utc).isoformat(), outcome, count, detail, job),
|
||
)
|
||
db.execute(
|
||
"DELETE FROM observations WHERE day<?", ((now - timedelta(days=730)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM market_daily WHERE day<?", ((now - timedelta(days=730)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM chokepoint_daily WHERE day<?", ((now - timedelta(days=730)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM upstream_runs WHERE day<?", ((now - timedelta(days=400)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM collections WHERE started_at<?", ((now - timedelta(days=90)).isoformat(),)
|
||
)
|
||
return dict(status=outcome, count=count, detail=detail, upstream=upstream_result)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import sys
|
||
|
||
if "--upstream-only" in sys.argv:
|
||
result = collect_upstream(force="--force" in sys.argv)
|
||
else:
|
||
result = collect(force="--force" in sys.argv)
|
||
print(datetime.now(timezone.utc).isoformat(), json.dumps(result, ensure_ascii=False), flush=True)
|
||
sys.exit(1 if result["status"] in ("error",) else 0)
|