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.
This commit is contained in:
13
.env.example
13
.env.example
@@ -4,20 +4,25 @@ FUEL_ADVISOR_DATA_DIR=/var/lib/fuel-advisor
|
||||
FUEL_DEFAULT_TYPE=Gazole
|
||||
FUEL_CACHE_TTL=21600
|
||||
|
||||
# Prix : flux officiel public.
|
||||
# Prix locaux : flux officiel public.
|
||||
FUEL_PRICES_URL='https://donnees.roulez-eco.fr/opendata/instantane'
|
||||
|
||||
# Pétrole : fournisseurs essayés dans l'ordre (stooq = CSV public, page = page publique de cotation).
|
||||
# FRED et EIA quotidien ne sont pas joignables depuis cette VM sans clé.
|
||||
FUEL_MARKET_PROVIDERS=stooq,page
|
||||
# Mettre les URL entre quotes pour le chargement par le shell.
|
||||
FUEL_MARKET_URL='https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv'
|
||||
FUEL_MARKET_PAGE_URL='https://tradingeconomics.com/commodity/brent-crude-oil'
|
||||
FUEL_MARKET_TTL=3600
|
||||
# Clé EIA gratuite (facultative) : débloque le Brent quotidien officiel si elle est fournie.
|
||||
# FUEL_EIA_API_KEY=
|
||||
|
||||
# Enseignes (OpenStreetMap/Nominatim) : durée de cache par zone.
|
||||
# Sources amont officielles (DGEC, bulletin UE, IMF PortWatch) : aucune clé requise.
|
||||
FUEL_BRAND_TTL=2592000
|
||||
|
||||
# Certaines sources publiques refusent les agents non navigateur.
|
||||
FUEL_HTTP_USER_AGENT='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36'
|
||||
|
||||
# Ollama n'est plus appelé : les anciennes variables OLLAMA_* sont ignorées.
|
||||
# Ollama : analyseur d'événements non structurés uniquement (jamais décideur).
|
||||
OLLAMA_URL=http://10.53.2.22:11434
|
||||
OLLAMA_MODEL=mistral-small3.2:24b
|
||||
OLLAMA_FALLBACK_MODEL=gemma4:12b
|
||||
|
||||
31
README.md
31
README.md
@@ -54,6 +54,21 @@ Deux graphiques sans dépendance externe (SVG généré côté navigateur) :
|
||||
|
||||
Les valeurs ne sont pas interpolées : un jour manquant n'est pas inventé.
|
||||
|
||||
### Sources amont historisées (mesurées depuis la VM)
|
||||
|
||||
| Source | Fréquence | État réel |
|
||||
|---|---|---|
|
||||
| DGEC – Brent daté (moyennes mensuelles) | mensuel, 2015→ | ✅ récupéré (140 points) |
|
||||
| DGEC – marge brute de raffinage sur Brent | mensuel, 2015→ | ✅ récupéré (USD/baril et EUR/tonne) |
|
||||
| DGEC – prix de vente HTT **et** TTC France par carburant | hebdomadaire, 2020→ | ✅ récupéré (418 points/carburant) |
|
||||
| Bulletin pétrolier UE – France TTC et hors taxes | hebdomadaire, ~2005→ | ✅ récupéré (1083 points/produit) |
|
||||
| IMF PortWatch (base du moniteur de l'IEA) – détroits | quotidien, différé | ✅ récupéré (Ormuz, Bab el-Mandeb, Suez, Malacca) |
|
||||
| BCE – taux USD/EUR | quotidien | ✅ récupéré |
|
||||
| Brent quotidien : FRED / EIA / Yahoo / Stooq | quotidien | ❌ FRED et Stooq injoignables depuis la VM (timeout, HTTP 503), Yahoo renvoie 429 ; EIA quotidien exige une clé gratuite. En attendant : page publique de cotation, source non officielle assumée |
|
||||
|
||||
Limite mesurée : GDELT répond par intermittence (429), l'API EIA quotidienne demande une clé gratuite
|
||||
(`FUEL_EIA_API_KEY` prévu mais non activé faute de clé). Aucune donnée n'est inventée quand une source manque.
|
||||
|
||||
### Cours du pétrole
|
||||
|
||||
Chaîne de fournisseurs, sans clé d'API, configurable avec `FUEL_MARKET_PROVIDERS` (défaut `stooq,page`) :
|
||||
@@ -65,6 +80,22 @@ Le taux de change vient de la **BCE** (API officielle sans clé), ce qui permet
|
||||
|
||||
**Pas de prévision pétrole → pompe** avant constitution et validation d'un historique suffisant.
|
||||
|
||||
## Collecte amont (séparée des favoris)
|
||||
|
||||
`collector.py` exécute deux collectes indépendantes :
|
||||
|
||||
- **prix locaux** : nécessite au moins un favori ;
|
||||
- **séries amont** : DGEC, bulletin UE, PortWatch, cotation quotidienne — collectées même sans favori,
|
||||
une fois par jour civil, avec nouvelle tentative le même jour en cas d'échec partiel.
|
||||
|
||||
```sh
|
||||
python3 collector.py --upstream-only --force # amorcer / vérifier les sources amont
|
||||
```
|
||||
|
||||
Tables : `upstream_series` (série, date, valeur, unité, source, horodatage), `chokepoint_daily`,
|
||||
`upstream_runs` (journal). API : `GET /api/upstream`. Chaque valeur affichée porte sa date, sa source
|
||||
et sa fraîcheur réelle ; « périmé » ou « date inconnue » ne devient jamais « stable ».
|
||||
|
||||
## Déploiement et maintenance
|
||||
|
||||
Configuration : `/etc/fuel-advisor.env` (voir `.env.example`). État/cache : `/var/lib/fuel-advisor/fuel.sqlite3`. Logs service : `/var/log/fuel-advisor.log`. Logs job : `/var/log/fuel-advisor-collect.log`.
|
||||
|
||||
26
app.py
26
app.py
@@ -308,6 +308,32 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self.send_json(dict(fuels=FUEL_TYPES, default_fuel=DEFAULT_FUEL))
|
||||
if path == "/api/status":
|
||||
return self.send_json(collector.status())
|
||||
if path == "/api/upstream":
|
||||
return self.send_json(
|
||||
dict(
|
||||
series=storage.latest_upstream(),
|
||||
history={
|
||||
name: storage.upstream_series(name, int(q.get("days", 400)))
|
||||
for name in (
|
||||
"dgec_brent_usd",
|
||||
"brent_usd_daily",
|
||||
"brent_eur_daily",
|
||||
"usd_per_eur",
|
||||
"dgec_margin_usd_per_bbl",
|
||||
"dgec_margin_eur_per_tonne",
|
||||
"fr_ttc_Gazole",
|
||||
"fr_htt_Gazole",
|
||||
"fr_ttc_E10",
|
||||
"fr_htt_E10",
|
||||
"eu_fr_diesel_ttc",
|
||||
"eu_fr_diesel_htt",
|
||||
)
|
||||
},
|
||||
chokepoints=storage.chokepoint_daily(int(q.get("chokepoint_days", 60))),
|
||||
note="Sources amont officielles. Chaque valeur porte sa date et sa source ; "
|
||||
"une donnée absente reste inconnue, jamais supposée stable.",
|
||||
)
|
||||
)
|
||||
if path in ("/api/vehicles", "/api/favorites"):
|
||||
return self.send_json(dict(items=storage.list_entities(path.split("/")[-1])))
|
||||
if path == "/api/geocode":
|
||||
|
||||
230
collector.py
230
collector.py
@@ -1,10 +1,24 @@
|
||||
"""Collecte quotidienne et relance horaire après échec, verrou interprocessus."""
|
||||
"""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():
|
||||
@@ -12,19 +26,190 @@ def status():
|
||||
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
|
||||
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 collect(load=None, market=None, force=False):
|
||||
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)
|
||||
|
||||
market = app.market_signal
|
||||
now = datetime.now(timezone.utc)
|
||||
day = now.astimezone(storage.PARIS).date().isoformat()
|
||||
storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -32,10 +217,10 @@ def collect(load=None, market=None, force=False):
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return {"status": "busy", "count": 0}
|
||||
return {"status": "busy", "count": 0, "upstream": upstream_result}
|
||||
favorites = storage.list_entities("favorites")
|
||||
if not favorites:
|
||||
return {"status": "no_favorites", "count": 0}
|
||||
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"
|
||||
@@ -45,9 +230,10 @@ def collect(load=None, market=None, force=False):
|
||||
and last
|
||||
and datetime.fromisoformat(last[0]).astimezone(storage.PARIS).date().isoformat() == day
|
||||
):
|
||||
return {"status": "skipped", "count": 0}
|
||||
return {"status": "skipped", "count": 0, "upstream": upstream_result}
|
||||
db.execute(
|
||||
"UPDATE collections SET status='error', detail='Collecte précédente interrompue' WHERE status='running'"
|
||||
"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(),)
|
||||
@@ -66,17 +252,7 @@ def collect(load=None, market=None, force=False):
|
||||
)
|
||||
]
|
||||
count = storage.record_observations(selected, now)
|
||||
# L'indisponibilité du pétrole ne doit pas annuler l'historique local.
|
||||
try:
|
||||
market_data = market() if market else {"trend": "unknown"}
|
||||
if market_data.get("trend") != "unknown" and market_data.get("date"):
|
||||
with storage.connect() as db:
|
||||
db.execute(
|
||||
"REPLACE INTO market_daily VALUES(?,?)",
|
||||
(market_data["date"], json.dumps(market_data)),
|
||||
)
|
||||
except Exception as exc:
|
||||
detail = f"Prix locaux collectés ; pétrole indisponible ({type(exc).__name__})"
|
||||
storage.sync_station_names(rows, now)
|
||||
if not selected:
|
||||
detail = "Aucune station dans les favoris actuels"
|
||||
except Exception as exc:
|
||||
@@ -86,22 +262,30 @@ def collect(load=None, market=None, force=False):
|
||||
"UPDATE collections SET finished_at=?, status=?, count=?, detail=? WHERE id=?",
|
||||
(datetime.now(timezone.utc).isoformat(), outcome, count, detail, job),
|
||||
)
|
||||
# Fenêtre glissante suffisante pour une future validation ; limiter le volume.
|
||||
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)
|
||||
return dict(status=outcome, count=count, detail=detail, upstream=upstream_result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
result = collect(force="--force" in sys.argv)
|
||||
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"] == "error" else 0)
|
||||
sys.exit(1 if result["status"] in ("error",) else 0)
|
||||
|
||||
126
storage.py
126
storage.py
@@ -8,7 +8,7 @@ import os
|
||||
import sqlite3
|
||||
import statistics
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
@@ -117,6 +117,119 @@ def sync_station_names(flux_rows, now=None):
|
||||
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)
|
||||
@@ -279,6 +392,17 @@ def connect():
|
||||
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);
|
||||
""")
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""Fixtures partagées : aucune base de production, aucun accès réseau."""
|
||||
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
|
||||
import brands
|
||||
@@ -15,6 +17,9 @@ def isolated_database(tmp_path, monkeypatch):
|
||||
# Aucun test ne doit interroger Nominatim ou un fournisseur de cours.
|
||||
monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: [])
|
||||
monkeypatch.setattr(market, "PROVIDERS", {})
|
||||
# Aucun test ne doit sortir sur le réseau pour les sources amont.
|
||||
collector = importlib.import_module("collector")
|
||||
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
|
||||
return tmp_path
|
||||
|
||||
|
||||
|
||||
@@ -20,11 +20,11 @@ def test_collect_overlapping_favorites_once_daily(store, collector):
|
||||
calls.append(1)
|
||||
return [sample(datetime.now(timezone.utc))]
|
||||
|
||||
out = collector.collect(load, lambda: {"trend": "unknown"}, force=True)
|
||||
out = collector.collect(load, force=True)
|
||||
assert out["status"] == "ok"
|
||||
assert out["count"] == 1
|
||||
assert len(calls) == 1
|
||||
assert collector.collect(load, lambda: {}, force=False)["status"] == "skipped"
|
||||
assert collector.collect(load, force=False)["status"] == "skipped"
|
||||
assert len(calls) == 1
|
||||
with store.connect() as db:
|
||||
assert db.execute("select count(*) from observations").fetchone()[0] == 1
|
||||
@@ -36,8 +36,8 @@ def test_failed_collection_logged_and_retryable(store, collector):
|
||||
def fail():
|
||||
raise OSError("source inaccessible")
|
||||
|
||||
assert collector.collect(fail, lambda: {}, force=True)["status"] == "error"
|
||||
out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], lambda: {}, force=False)
|
||||
assert collector.collect(fail, force=True)["status"] == "error"
|
||||
out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], force=False)
|
||||
assert out["status"] == "ok"
|
||||
|
||||
|
||||
@@ -45,4 +45,4 @@ def test_empty_favorites_does_not_download(store, collector):
|
||||
def forbidden():
|
||||
raise AssertionError("Aucun téléchargement sans favori")
|
||||
|
||||
assert collector.collect(forbidden, forbidden)["status"] == "no_favorites"
|
||||
assert collector.collect(forbidden)["status"] == "no_favorites"
|
||||
|
||||
119
tests/test_upstream.py
Normal file
119
tests/test_upstream.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch)."""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
import upstream
|
||||
|
||||
|
||||
def make_xlsx(sheet_name, cells, strings=None):
|
||||
"""Construit un classeur minimal respectant la structure réelle lue sur la VM."""
|
||||
text_values = {ref: value for ref, value in cells.items() if isinstance(value, str)}
|
||||
numeric = {ref: value for ref, value in cells.items() if not isinstance(value, str)}
|
||||
shared = list(dict.fromkeys(text_values.values()))
|
||||
index = {value: position for position, value in enumerate(shared)}
|
||||
|
||||
def cell_xml(ref, value):
|
||||
if isinstance(value, str):
|
||||
return f'<c r="{ref}" t="s"><v>{index[value]}</v></c>'
|
||||
return f'<c r="{ref}"><v>{value}</v></c>'
|
||||
|
||||
sheet_rows = {}
|
||||
for ref in list(numeric) + list(text_values):
|
||||
row = ''.join(ch for ch in ref if ch.isdigit())
|
||||
sheet_rows.setdefault(int(row), []).append(cell_xml(ref, {**numeric, **text_values}[ref]))
|
||||
body = ''.join(f'<row r="{number}">{"".join(cells_xml)}</row>' for number, cells_xml in sorted(sheet_rows.items()))
|
||||
shared_xml = ('<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
+ ''.join(f'<si><t>{value}</t></si>' for value in shared) + '</sst>')
|
||||
workbook = ('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
f'<sheets><sheet name="{sheet_name}" sheetId="1" r:id="rId1"/></sheets></workbook>')
|
||||
rels = ('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>')
|
||||
sheet = ('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
f'<sheetData>{body}</sheetData></worksheet>')
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, 'w') as archive:
|
||||
archive.writestr('xl/workbook.xml', workbook)
|
||||
archive.writestr('xl/_rels/workbook.xml.rels', rels)
|
||||
archive.writestr('xl/sharedStrings.xml', shared_xml)
|
||||
archive.writestr('xl/worksheets/sheet1.xml', sheet)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_excel_date_conversion_and_rejection():
|
||||
assert upstream.excel_date(42005) == '2015-01-01'
|
||||
assert upstream.excel_date(46272) == '2026-09-07'
|
||||
assert upstream.excel_date('2025') is None
|
||||
assert upstream.excel_date(None) is None
|
||||
|
||||
|
||||
def test_parse_dgec_brent_keeps_monthly_rows_only():
|
||||
raw = make_xlsx('Cours du Brent', {'A3': 42005, 'B3': 47.708, 'A4': 42036, 'B4': 58.0955, 'A157': '2025', 'B157': 69.1})
|
||||
out = upstream.parse_dgec_brent(raw)
|
||||
assert out == [{'day': '2015-01-01', 'value': 47.71}, {'day': '2015-02-01', 'value': 58.1}]
|
||||
|
||||
|
||||
def test_parse_dgec_brent_rejects_garbage():
|
||||
with pytest.raises(ValueError):
|
||||
upstream.parse_dgec_brent(make_xlsx('Cours du Brent', {'B1': 'rien'}))
|
||||
|
||||
|
||||
def test_parse_dgec_margin_keeps_both_units():
|
||||
raw = make_xlsx('Marge brute raffinage sur Brent', {'A3': 42005, 'B3': 6.9877, 'C3': 45.253})
|
||||
assert upstream.parse_dgec_margin(raw) == [{'day': '2015-01-01', 'usd_per_bbl': 6.99, 'eur_per_tonne': 45.25}]
|
||||
|
||||
|
||||
def test_parse_dgec_prices_splits_htt_and_ttc():
|
||||
cells = {'A3': 46272, 'B2': 'Gazole', 'H2': 'Gazole', 'B3': 1.653, 'H3': 1.99}
|
||||
out = upstream.parse_dgec_prices(make_xlsx('Carburants routiers', cells))
|
||||
assert out == [{'day': '2026-09-07', 'htt': {'Gazole': 1.653}, 'ttc': {'Gazole': 1.99}}]
|
||||
|
||||
|
||||
def test_parse_eu_bulletin_converts_thousands_of_litres():
|
||||
cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_with_tax_diesel', 'CN4': 2041.66,
|
||||
'CO1': 'FR_price_with_tax_euro95', 'CO4': 1899.99}
|
||||
out = upstream.parse_eu_bulletin(make_xlsx('Prices with taxes', cells))
|
||||
assert out == [{'day': '2026-09-07', 'prices': {'diesel': 2.042, 'euro95': 1.9}}]
|
||||
|
||||
|
||||
def test_parse_eu_bulletin_accepts_without_tax_sheet():
|
||||
# Le bulletin nomme le second onglet « Prices wo taxes » : les en-têtes diffèrent.
|
||||
cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_wo_tax_diesel', 'CN4': 1500.0}
|
||||
out = upstream.parse_eu_bulletin(make_xlsx('Prices wo taxes', cells), 'FR', 'Prices wo taxes')
|
||||
assert out == [{'day': '2026-09-07', 'prices': {'diesel': 1.5}}]
|
||||
|
||||
|
||||
def test_parse_eu_bulletin_rejects_missing_country():
|
||||
raw = make_xlsx('Prices with taxes', {'A3': 'Date', 'A4': 46272, 'CN1': 'BE_price_with_tax_diesel', 'CN4': 1500})
|
||||
with pytest.raises(ValueError):
|
||||
upstream.parse_eu_bulletin(raw)
|
||||
|
||||
|
||||
def test_parse_chokepoints_keeps_latest_per_watched_strait():
|
||||
payload = json.dumps({'features': [
|
||||
{'attributes': {'date': '2026-08-30', 'portname': 'Strait of Hormuz', 'n_tanker': 40, 'n_total': 90}},
|
||||
{'attributes': {'date': '2026-09-06', 'portname': 'Strait of Hormuz', 'n_tanker': 2, 'n_total': 6,
|
||||
'capacity_tanker': 60280, 'capacity': 150000}},
|
||||
{'attributes': {'date': '2026-09-06', 'portname': 'Bab el-Mandeb Strait', 'n_tanker': 6, 'n_total': 23}},
|
||||
{'attributes': {'date': '2026-09-06', 'portname': 'Port of Nantes', 'n_tanker': 99}},
|
||||
]}).encode()
|
||||
out = upstream.parse_chokepoints(payload)
|
||||
assert set(out) == {'Strait of Hormuz', 'Bab el-Mandeb Strait'}
|
||||
assert out['Strait of Hormuz']['day'] == '2026-09-06'
|
||||
assert out['Strait of Hormuz']['transit_tankers'] == 2
|
||||
assert out['Strait of Hormuz']['capacity_total'] == 150000
|
||||
|
||||
|
||||
def test_parse_chokepoints_rejects_garbage():
|
||||
with pytest.raises(ValueError):
|
||||
upstream.parse_chokepoints(b'{"error": "bad query"}')
|
||||
|
||||
|
||||
def test_freshness_never_assumes_current():
|
||||
assert upstream.freshness('2026-09-10', today=__import__('datetime').date(2026, 9, 12)) == {
|
||||
'state': 'fresh', 'age_days': 2}
|
||||
assert upstream.freshness('2026-07-01', today=__import__('datetime').date(2026, 9, 12))['state'] == 'stale'
|
||||
assert upstream.freshness(None) == {'state': 'unknown', 'age_days': None}
|
||||
98
tests/test_upstream_store.py
Normal file
98
tests/test_upstream_store.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""Historisation des séries amont et orchestration de la collecte amont."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import collector
|
||||
import storage
|
||||
|
||||
|
||||
def test_upstream_series_roundtrip_and_deduplication(store):
|
||||
rows = [dict(day="2026-01-01", value=80.0), dict(day="2026-02-01", value=82.5)]
|
||||
assert storage.save_upstream("dgec_brent_usd", rows, "USD/baril", "DGEC", datetime.now(timezone.utc)) == 2
|
||||
assert [r["value"] for r in storage.upstream_series("dgec_brent_usd")] == [80.0, 82.5]
|
||||
storage.save_upstream("dgec_brent_usd", [dict(day="2026-02-01", value=83.0)], "USD/baril", "DGEC")
|
||||
assert [r["value"] for r in storage.upstream_series("dgec_brent_usd")] == [80.0, 83.0]
|
||||
|
||||
|
||||
def test_save_upstream_ignores_invalid_values(store):
|
||||
assert (
|
||||
storage.save_upstream(
|
||||
"x",
|
||||
[
|
||||
dict(day="2026-01-01", value=float("nan")),
|
||||
dict(day=None, value=1.0),
|
||||
dict(day="2026-01-02", value="n/a"),
|
||||
],
|
||||
"unit",
|
||||
"src",
|
||||
)
|
||||
== 0
|
||||
)
|
||||
assert storage.upstream_series("x") == []
|
||||
|
||||
|
||||
def test_latest_upstream_reports_real_freshness(store):
|
||||
today = datetime.now(timezone.utc).date()
|
||||
store.save_upstream("s1", [dict(day=today.isoformat(), value=1.0)], "EUR/L", "src")
|
||||
store.save_upstream("s2", [dict(day="2015-01-01", value=2.0)], "EUR/L", "src")
|
||||
latest = store.latest_upstream()
|
||||
assert latest["s1"]["freshness"] == "fresh"
|
||||
assert latest["s2"]["freshness"] == "stale"
|
||||
assert latest["s2"]["age_days"] > 1000
|
||||
|
||||
|
||||
def test_chokepoints_history_keeps_days(store):
|
||||
entries = {
|
||||
"Strait of Hormuz": dict(
|
||||
day="2026-09-06",
|
||||
transit_tankers=2,
|
||||
transit_total=6,
|
||||
capacity_tankers=60280,
|
||||
capacity_total=150000,
|
||||
)
|
||||
}
|
||||
assert store.save_chokepoints(entries, "IMF PortWatch") == 1
|
||||
store.save_chokepoints(entries, "IMF PortWatch")
|
||||
history = store.chokepoint_daily(60)
|
||||
assert list(history) == ["Strait of Hormuz"]
|
||||
assert len(history["Strait of Hormuz"]) == 1
|
||||
assert history["Strait of Hormuz"][0]["transit_tankers"] == 2
|
||||
|
||||
|
||||
def test_collect_upstream_runs_once_per_day_and_lists_failures(store, monkeypatch):
|
||||
calls = []
|
||||
|
||||
def good():
|
||||
calls.append("good")
|
||||
return [
|
||||
dict(series="test_series", unit="EUR/L", source="test", rows=[dict(day="2026-09-01", value=1.5)])
|
||||
]
|
||||
|
||||
def broken():
|
||||
calls.append("broken")
|
||||
raise OSError("source en panne")
|
||||
|
||||
assert collector.collect_upstream(force=True, sources={"good": good})["status"] == "ok"
|
||||
assert collector.collect_upstream(sources={"good": good})["status"] == "skipped"
|
||||
assert calls.count("good") == 1
|
||||
# Un échec partiel ne doit pas empêcher une nouvelle tentative le même jour.
|
||||
out = collector.collect_upstream(force=True, sources={"good": good, "broken": broken})
|
||||
assert out["status"] == "partial"
|
||||
assert "broken" in out["detail"] and "OSError" in out["detail"]
|
||||
assert store.upstream_series("test_series")[0]["value"] == 1.5
|
||||
|
||||
|
||||
def test_collect_upstream_reports_total_failure(store):
|
||||
def broken():
|
||||
raise OSError("hors ligne")
|
||||
|
||||
out = collector.collect_upstream(force=True, sources={"broken": broken})
|
||||
assert out["status"] == "error"
|
||||
assert store.latest_upstream() == {}
|
||||
|
||||
|
||||
def test_collect_still_returns_no_favorites_with_upstream(store, monkeypatch):
|
||||
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
|
||||
out = collector.collect(lambda: [], force=True)
|
||||
assert out["status"] == "no_favorites"
|
||||
assert "upstream" in out
|
||||
23
ui.js
23
ui.js
@@ -3,7 +3,7 @@ const $=id=>document.getElementById(id);
|
||||
const esc=x=>String(x??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const num=(n,d=0)=>Number.isFinite(n)?n.toLocaleString('fr-FR',{minimumFractionDigits:d,maximumFractionDigits:d}):'—';
|
||||
const stamp=s=>s?new Date(s).toLocaleString('fr-FR'):'—';
|
||||
let vehicles=[],favorites=[],coords=null,sequence=0;
|
||||
let vehicles=[],favorites=[],coords=null,sequence=0,upstream=null;
|
||||
async function api(path,method='GET',body){
|
||||
const controller=new AbortController(), timer=setTimeout(()=>controller.abort(),75000);
|
||||
try{
|
||||
@@ -45,6 +45,23 @@ async function geocode(){
|
||||
try{const d=await api('/api/geocode?q='+encodeURIComponent(query));if(ticket!==sequence)return;$('favorite').value='';locationSet(d.lat,d.lon,d.label);status('Lieu trouvé. Vous pouvez l’enregistrer en favori.');}
|
||||
catch(e){if(ticket===sequence)status(e.message,true);}finally{$('search').disabled=false;}
|
||||
}
|
||||
const SERIES_LABELS={dgec_brent_usd:'Brent, moyenne mensuelle (DGEC)',brent_usd_daily:'Brent, cotation quotidienne',brent_eur_daily:'Brent converti en euros',usd_per_eur:'Taux USD/EUR (BCE)',dgec_margin_usd_per_bbl:'Marge brute de raffinage (USD/baril)',dgec_margin_eur_per_tonne:'Marge brute de raffinage (EUR/tonne)',fr_ttc_Gazole:'Gazole France TTC (DGEC)',fr_htt_Gazole:'Gazole France hors taxes (DGEC)',fr_ttc_E10:'E10 France TTC (DGEC)',fr_htt_E10:'E10 France hors taxes (DGEC)',eu_fr_diesel_ttc:'Gazole France TTC (bulletin UE)',eu_fr_diesel_htt:'Gazole France hors taxes (bulletin UE)'};
|
||||
const FRESHNESS={fresh:['à jour','tone-none'],seasoned:['donnée ancienne','muted'],stale:['périmée','tone-refuel'],unknown:['date inconnue','muted']};
|
||||
function upstreamBlock(){
|
||||
if(!upstream||!upstream.series||!Object.keys(upstream.series).length){
|
||||
return '<p class="hint">Aucune donnée amont enregistrée pour l’instant. La collecte amont est quotidienne ; lancez « Actualiser » pour l’amorcer.</p>';
|
||||
}
|
||||
const series=Object.entries(upstream.series).map(([key,item])=>{
|
||||
const [label,tone]=FRESHNESS[item.freshness]||FRESHNESS.unknown;
|
||||
return `<div class="station"><div><strong>${esc(SERIES_LABELS[key]||key)}</strong><p class="hint">${esc(item.source||'')} · ${esc(item.day)} · <span class="${tone}">${label}${item.age_days!==null&&item.age_days!==undefined?` (${item.age_days} j)`:''}</span></p></div><div class="price">${num(item.value,3)} <small>${esc(item.unit||'')}</small></div></div>`;
|
||||
}).join('');
|
||||
const straits=Object.entries(upstream.chokepoints||{}).map(([name,points])=>{
|
||||
const last=points.at(-1)||{},first=points[0]||{};
|
||||
const delta=(last.transit_tankers!=null&&first.transit_tankers!=null)?last.transit_tankers-first.transit_tankers:null;
|
||||
return `<div class="station"><div><strong>${esc(name)}</strong><p class="hint">${esc(last.day||'')} · pétroliers ${last.transit_tankers??'—'}/${last.transit_total??'—'} navires · capacité pétroliers ${last.capacity_tankers?num(last.capacity_tankers/1000,0)+' k':'—'}</p><p class="hint">${esc(last.source||'')} · ${points.length} relevé(s)</p></div><div class="price">${delta===null?'—':(delta>0?'+':'')+num(delta,0)}<small> navires</small></div></div>`;
|
||||
}).join('');
|
||||
return `<div>${series}</div>${straits?`<h3>Passages observés (détroits)</h3><div>${straits}</div><p class="hint">Volumes journaliers par détroit, source IMF PortWatch utilisée par l’IEA. La publication est différée de plusieurs jours : la date affichée est celle de l’observation, pas celle du jour.</p>`:''}`;
|
||||
}
|
||||
function sparkline(points,width=150,height=42){
|
||||
const values=points.map(p=>p.price),lo=Math.min(...values),hi=Math.max(...values),span=Math.max(.02,hi-lo);
|
||||
const first=new Date(points[0].day+'T12:00:00').getTime(),last=new Date(points.at(-1).day+'T12:00:00').getTime();
|
||||
@@ -79,13 +96,13 @@ function render(d){
|
||||
$('result').innerHTML=`<section class="card"><div class="eyebrow">Quand ravitailler · ${esc(d.fuel)}</div><h2 class="verdict tone-${esc(d.action)}">${esc(d.label)}</h2>${metrics}<ul class="reasons">${reasons}</ul><div class="tags"><span>Calcul explicable · sans IA</span><span>Évolution future inconnue</span></div></section>
|
||||
<section class="card"><div class="eyebrow">Où acheter</div><h2>Les prix autour de vous</h2>${d.price_warning?`<p class="notice">${esc(d.price_warning)}</p>`:''}${d.brands_warning?`<p class="hint">${esc(d.brands_warning)}</p>`:''}${s.count?`<div class="metrics"><div class="metric"><strong>${num(s.min,3)}</strong><span>minimum €/L</span></div><div class="metric"><strong>${num(s.median,3)}</strong><span>médiane €/L</span></div><div class="metric"><strong>${num(s.max,3)}</strong><span>maximum €/L</span></div></div><p class="hint">${s.count} stations comparées · ${s.best_tie_count} au meilleur prix · ${d.stations.length} affichées. Prix déclarés depuis moins de ${d.price_max_age_days} jours.</p><details><summary>Répartition des prix</summary><div class="buckets">${s.price_buckets.map(b=>`<span class="bucket">${num(b.price,3)} € · ${b.count}</span>`).join('')}</div></details>`:''}<div>${stations}</div><p class="hint">${esc(d.distance_note)} Un bon prix local ne signifie pas que c’est le bon moment pour remplir le réservoir.</p></section>
|
||||
<section class="card"><div class="eyebrow">Historique local · 30 jours</div><h2>Ce que les prix ont réellement fait</h2><p>${esc(h.summary)}</p>${h.confidence==='limited'?'<p class="notice">Panel réduit : tendance peu représentative du secteur.</p>':''}<h3>Moyenne des prix enregistrés</h3>${averageChart(h.average_series)}<h3>Évolution par station</h3>${stationCards(h.stations_series)}<p class="hint">${h.days||0} jours observés. Moyenne calculée sur les relevés réellement enregistrés ce jour-là ; les stations apparaissent à partir de leur premier relevé. Dates manquantes non interpolées, aucune prévision. Enregistrez ce lieu en favori pour prolonger son suivi.</p></section>
|
||||
<section class="card compact"><h2>Cours du pétrole</h2><p class="hint">${esc(d.market?.summary||'Indisponible')}</p><p class="hint">${d.market?.reference?esc(d.market.reference):''} Le pétrole n’est pas utilisé pour prédire un délai de répercussion à la pompe : il faut d’abord constituer et valider un historique local.</p></section>`;
|
||||
<section class="card"><div class="eyebrow">Marché amont</div><h2>Ce qui pousse les prix, en amont</h2><p>${esc(d.market?.summary||'Cotation indisponible')}</p><p class="hint">${d.market?.reference?esc(d.market.reference):''}</p>${upstreamBlock()}<p class="hint">Ces indicateurs ne décident pas du conseil. Ils servent à qualifier la tendance et, plus tard, à mesurer un décalage réel vers la pompe. Un chiffre sans date fiable n’est pas utilisé.</p></section>`;
|
||||
status('Conseil calculé à '+stamp(d.generated_at));
|
||||
}
|
||||
function basePayload(){if(!coords)throw new Error('Choisissez d’abord un lieu.');return {...coords,radius_km:Number($('radius').value),fuel:$('fuel').value};}
|
||||
async function calculate(extra={}){
|
||||
const ticket=++sequence;$('advise').disabled=true;status('Comparaison des prix et calcul…');$('result').innerHTML='<section class="card loading">Vérification des données et de votre marge de sécurité…</section>';
|
||||
try{const data=await api('/api/advice','POST',{...basePayload(),...extra});if(ticket===sequence)render(data);}
|
||||
try{upstream=await api('/api/upstream').catch(()=>null);const data=await api('/api/advice','POST',{...basePayload(),...extra});if(ticket===sequence)render(data);}
|
||||
catch(e){if(ticket===sequence){status(e.message,true);$('result').innerHTML='<section class="card"><p class="error">'+esc(e.message)+'</p></section>';}}
|
||||
finally{$('advise').disabled=false;}
|
||||
}
|
||||
|
||||
259
upstream.py
Normal file
259
upstream.py
Normal file
@@ -0,0 +1,259 @@
|
||||
"""Sources amont officielles : DGEC, bulletin pétrolier UE, détroits maritimes (IMF PortWatch).
|
||||
|
||||
Aucune clé d'API. Aucune donnée inventée : une source absente reste absente et est signalée
|
||||
avec sa fraîcheur. Les parseurs sont purs (ils reçoivent des octets) pour rester testables.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
USER_AGENT = (
|
||||
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36'
|
||||
)
|
||||
EXCEL_EPOCH = datetime(1899, 12, 30)
|
||||
|
||||
DGEC_BASE = 'https://www.ecologie.gouv.fr/sites/default/files/documents/'
|
||||
DGEC_FILES = {
|
||||
'brent': 'Historique%20du%20cours%20du%20Brent%20depuis%202015%20%28moyennes%20mensuelles%29_0.xlsx',
|
||||
'margin': ('Historique%20de%20la%20marge%20brute%20de%20raffinage%20sur%20Brent%20depuis%202015'
|
||||
'%20%28moyennes%20mensuelles%29.xlsx'),
|
||||
'prices': 'Prix%20HTT%20et%20TTC%20depuis%20janvier%202020_0.xlsx',
|
||||
}
|
||||
FUEL_COLUMNS = {
|
||||
'Gazole': 'Gazole', 'SP95': 'Super SP95-E5', 'E10': 'Super SP95-E10',
|
||||
'SP98': 'Super SP98', 'E85': 'Superéthanol E85', 'GPLc': 'GPLc',
|
||||
}
|
||||
EU_BULLETIN_PAGE = 'https://energy.ec.europa.eu/data-and-analysis/weekly-oil-bulletin_en'
|
||||
EU_FUELS = {'Gazole': 'diesel', 'SP95': 'euro95', 'SP98': 'euro98', 'E10': 'euro95', 'E85': 'euro95'}
|
||||
PORTWATCH_QUERY = ('https://services9.arcgis.com/weJ1QsnbMYJlCHdG/arcgis/rest/services/'
|
||||
'Daily_Chokepoints_Data/FeatureServer/0/query')
|
||||
WATCHED_CHOKEPOINTS = ('Strait of Hormuz', 'Bab el-Mandeb Strait', 'Suez Canal', 'Malacca Strait')
|
||||
|
||||
|
||||
def fetch_bytes(url, timeout=60, limit=12_000_000):
|
||||
request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT, 'Accept': '*/*'})
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return response.read(limit)
|
||||
|
||||
|
||||
def excel_date(serial):
|
||||
"""Convertit une date série Excel (avec le bug 1900) en date ISO. None si illisible."""
|
||||
try:
|
||||
value = float(serial)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not 20000 <= value <= 60000:
|
||||
return None
|
||||
return (EXCEL_EPOCH + timedelta(days=value)).date().isoformat()
|
||||
|
||||
|
||||
def xlsx_cells(raw, sheet=None):
|
||||
"""Cellules {'A1': valeur} d'une feuille, valeurs partagées résolues."""
|
||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||
workbook = archive.read('xl/workbook.xml').decode('utf-8', 'replace')
|
||||
rels = archive.read('xl/_rels/workbook.xml.rels').decode('utf-8', 'replace')
|
||||
targets = dict(re.findall(r'Id="(rId\d+)"[^>]*Target="([^"]+)"', rels))
|
||||
sheets = dict((name, targets.get(rid)) for name, rid in
|
||||
re.findall(r'<sheet[^>]*name="([^"]+)"[^>]*r:id="(rId\d+)"', workbook))
|
||||
if not sheets:
|
||||
raise ValueError('classeur sans feuille')
|
||||
name = sheet if sheet in sheets else next(iter(sheets))
|
||||
strings = []
|
||||
if 'xl/sharedStrings.xml' in archive.namelist():
|
||||
root = ET.fromstring(archive.read('xl/sharedStrings.xml'))
|
||||
strings = [''.join(node.text or '' for node in item.iter()) for item in root]
|
||||
sheet_xml = ET.fromstring(archive.read('xl/' + sheets[name].lstrip('/')))
|
||||
cells = {}
|
||||
for cell in sheet_xml.iter(NS + 'c'):
|
||||
value = cell.find(NS + 'v')
|
||||
if value is None or value.text is None:
|
||||
continue
|
||||
reference = cell.attrib.get('r', '')
|
||||
if not reference:
|
||||
continue
|
||||
cells[reference] = strings[int(value.text)] if cell.attrib.get('t') == 's' else value.text
|
||||
return cells
|
||||
|
||||
|
||||
def column_headers(cells, row=1):
|
||||
"""En-têtes de la ligne ``row`` : {'CN': 'FR_price_with_tax_euro95'}."""
|
||||
out = {}
|
||||
for reference, value in cells.items():
|
||||
match = re.fullmatch(r'([A-Z]{1,3})%d' % row, reference)
|
||||
if match and isinstance(value, str):
|
||||
out[match.group(1)] = value
|
||||
return out
|
||||
|
||||
|
||||
def _rows_by_date(cells, date_column='A', first_row=4):
|
||||
"""Associe chaque ligne à sa date ISO via la colonne de dates."""
|
||||
out = {}
|
||||
for reference, value in cells.items():
|
||||
match = re.fullmatch(re.escape(date_column) + r'(\d+)', reference)
|
||||
if not match:
|
||||
continue
|
||||
day = excel_date(value)
|
||||
if day and int(match.group(1)) >= first_row:
|
||||
out[int(match.group(1))] = day
|
||||
return out
|
||||
|
||||
|
||||
def parse_dgec_brent(raw, sheet='Cours du Brent'):
|
||||
"""Cours moyen mensuel du Brent daté (DGEC, $/baril), lignes annuelles écartées."""
|
||||
cells = xlsx_cells(raw, sheet)
|
||||
out = []
|
||||
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
|
||||
value = cells.get('B%d' % row)
|
||||
try:
|
||||
price = float(value)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if 5 <= price <= 400:
|
||||
out.append(dict(day=day, value=round(price, 2)))
|
||||
if not out:
|
||||
raise ValueError('cours du Brent illisible')
|
||||
return out
|
||||
|
||||
|
||||
def parse_dgec_margin(raw, sheet='Marge brute raffinage sur Brent'):
|
||||
"""Marge brute de raffinage sur Brent (DGEC) en $/baril et en €/tonne."""
|
||||
cells = xlsx_cells(raw, sheet)
|
||||
out = []
|
||||
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
|
||||
try:
|
||||
usd = float(cells.get('B%d' % row))
|
||||
eur = float(cells.get('C%d' % row))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if -20 <= usd <= 100 and -100 <= eur <= 800:
|
||||
out.append(dict(day=day, usd_per_bbl=round(usd, 2), eur_per_tonne=round(eur, 2)))
|
||||
if not out:
|
||||
raise ValueError('marge de raffinage illisible')
|
||||
return out
|
||||
|
||||
|
||||
def parse_dgec_prices(raw, sheet='Carburants routiers'):
|
||||
"""Prix moyens français HTT et TTC par carburant (DGEC)."""
|
||||
cells = xlsx_cells(raw, sheet)
|
||||
headers = column_headers(cells, 2)
|
||||
htt = {letter: name for letter, name in headers.items() if letter < 'H'}
|
||||
ttc = {letter: name for letter, name in headers.items() if letter >= 'H'}
|
||||
out = []
|
||||
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
|
||||
entry = dict(day=day, htt={}, ttc={})
|
||||
for letter, name in htt.items():
|
||||
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
|
||||
try:
|
||||
entry['htt'][fuel] = round(float(cells['%s%d' % (letter, row)]), 3)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
for letter, name in ttc.items():
|
||||
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
|
||||
try:
|
||||
entry['ttc'][fuel] = round(float(cells['%s%d' % (letter, row)]), 3)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if entry['htt'] or entry['ttc']:
|
||||
out.append(entry)
|
||||
if not out:
|
||||
raise ValueError('prix HTT/TTC illisibles')
|
||||
return out
|
||||
|
||||
|
||||
def parse_eu_bulletin(raw, country='FR', sheet='Prices with taxes'):
|
||||
"""Prix hebdomadaires par pays du bulletin pétrolier UE (€/1000 L -> €/L)."""
|
||||
cells = xlsx_cells(raw, sheet)
|
||||
headers = column_headers(cells, 1)
|
||||
columns = {}
|
||||
for letter, name in headers.items():
|
||||
match = re.fullmatch(re.escape(country) + r'_price_(?:with_tax|wo_tax|without_tax)_(\w+)', name)
|
||||
if match:
|
||||
columns[letter] = match.group(1)
|
||||
if not columns:
|
||||
raise ValueError(f'pays {country} absent du bulletin')
|
||||
out = []
|
||||
for row, day in sorted(_rows_by_date(cells, 'A', 4).items()):
|
||||
entry = dict(day=day, prices={})
|
||||
for letter, product in columns.items():
|
||||
try:
|
||||
entry['prices'][product] = round(float(cells['%s%d' % (letter, row)]) / 1000, 3)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if entry['prices']:
|
||||
out.append(entry)
|
||||
if not out:
|
||||
raise ValueError('aucune semaine exploitable')
|
||||
return out
|
||||
|
||||
|
||||
def parse_chokepoints(payload):
|
||||
"""Dernière valeur connue par détroit surveillé (source IMF PortWatch)."""
|
||||
try:
|
||||
features = json.loads(payload)['features']
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise ValueError('flux PortWatch illisible') from None
|
||||
latest = {}
|
||||
for feature in features:
|
||||
attributes = feature.get('attributes') or {}
|
||||
name = attributes.get('portname')
|
||||
day = str(attributes.get('date') or '')
|
||||
if name not in WATCHED_CHOKEPOINTS or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', day):
|
||||
continue
|
||||
if name not in latest or day > latest[name]['day']:
|
||||
latest[name] = dict(
|
||||
day=day, transit_tankers=attributes.get('n_tanker'), transit_total=attributes.get('n_total'),
|
||||
capacity_tankers=attributes.get('capacity_tanker'), capacity_total=attributes.get('capacity'),
|
||||
)
|
||||
return latest
|
||||
|
||||
|
||||
def freshness(day, today=None, max_age_days=10):
|
||||
"""Fraîcheur d'une observation jamais présentée comme « à jour » par défaut."""
|
||||
today = today or datetime.now(timezone.utc).date()
|
||||
try:
|
||||
age = (today - date.fromisoformat(day)).days
|
||||
except (TypeError, ValueError):
|
||||
return dict(state='unknown', age_days=None)
|
||||
if age < 0:
|
||||
return dict(state='unknown', age_days=age)
|
||||
return dict(state='fresh' if age <= max_age_days else 'stale', age_days=age)
|
||||
|
||||
|
||||
def dgec_urls():
|
||||
return {key: DGEC_BASE + name for key, name in DGEC_FILES.items()}
|
||||
|
||||
|
||||
def eu_bulletin_url():
|
||||
"""Le bulletin hebdomadaire est publié derrière une URL à identifiant variable."""
|
||||
html = fetch_bytes(EU_BULLETIN_PAGE, timeout=45).decode('utf-8', 'replace')
|
||||
links = re.findall(r'href="([^"]*filename=[^"]*\.xlsx)"', html, re.I)
|
||||
history = [link for link in links if re.search(r'histor', urllib.parse.unquote(link), re.I)]
|
||||
if not history:
|
||||
raise ValueError('fichier d’historique du bulletin introuvable')
|
||||
url = history[0].replace('&', '&')
|
||||
return url if url.startswith('http') else 'https://energy.ec.europa.eu' + url
|
||||
|
||||
|
||||
def fetch_chokepoints(days=6, today=None):
|
||||
"""Détroits surveillés : quelques jours suffisent, la source a du retard."""
|
||||
today = today or datetime.now(timezone.utc).date()
|
||||
query = urllib.parse.urlencode({
|
||||
'where': f"date >= DATE '{today.isoformat()}'", 'outFields': '*',
|
||||
'returnGeometry': 'false', 'orderByFields': 'date DESC', 'resultRecordCount': '200', 'f': 'json',
|
||||
})
|
||||
for offset in range(days, days + 12, 6):
|
||||
lookback = (today - timedelta(days=offset)).isoformat()
|
||||
probe = query.replace(urllib.parse.quote(today.isoformat()), urllib.parse.quote(lookback))
|
||||
payload = fetch_bytes(f'{PORTWATCH_QUERY}?{probe}', timeout=40)
|
||||
found = parse_chokepoints(payload)
|
||||
if found:
|
||||
return found, None
|
||||
return {}, 'PortWatch : aucune donnée récente (retard de publication ou service indisponible)'
|
||||
Reference in New Issue
Block a user