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:
@@ -22,6 +22,12 @@ FUEL_BRAND_TTL=2592000
|
|||||||
# Certaines sources publiques refusent les agents non navigateur.
|
# 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'
|
FUEL_HTTP_USER_AGENT='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36'
|
||||||
|
|
||||||
|
# Prix locaux : actualisation forcée lors d'un conseil si le flux est plus vieux que ce délai.
|
||||||
|
FUEL_LOCAL_MAX_AGE=900
|
||||||
|
# Nombre d'articles traités par passage (une extraction prend ~2-3 min avec le modèle 24b).
|
||||||
|
FUEL_NEWS_MAX_PER_RUN=3
|
||||||
|
FUEL_PROMO_MAX_PER_RUN=3
|
||||||
|
|
||||||
# Ollama : analyseur d'événements non structurés uniquement (jamais décideur).
|
# Ollama : analyseur d'événements non structurés uniquement (jamais décideur).
|
||||||
OLLAMA_URL=http://10.53.2.22:11434
|
OLLAMA_URL=http://10.53.2.22:11434
|
||||||
OLLAMA_MODEL=mistral-small3.2:24b
|
OLLAMA_MODEL=mistral-small3.2:24b
|
||||||
|
|||||||
50
README.md
50
README.md
@@ -80,6 +80,56 @@ 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.
|
**Pas de prévision pétrole → pompe** avant constitution et validation d'un historique suffisant.
|
||||||
|
|
||||||
|
## Ordonnanceur multi-fréquences
|
||||||
|
|
||||||
|
Un seul point d'entrée, prévu **toutes les 10 minutes** dans `/etc/crontabs/root` :
|
||||||
|
|
||||||
|
```sh
|
||||||
|
*/10 * * * * /opt/fuel-advisor/schedule.sh >> /var/log/fuel-advisor-collect.log 2>&1
|
||||||
|
```
|
||||||
|
|
||||||
|
`schedule.sh` lance `scheduler.py --run` : chaque collecteur décide lui-même s'il est dû, selon sa
|
||||||
|
cadence, sa fenêtre horaire et sa dernière exécution (nouvelle tentative plus rapide après un échec).
|
||||||
|
|
||||||
|
| Collecteur | Source | Fréquence | Fenêtre |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `local_prices` | prix-carburants.gouv.fr (flux instantané) | chaque heure, 24/7 | toujours |
|
||||||
|
| `market_daily` | Brent quotidien (Stooq → page publique ; clé EIA si fournie) | 1×/jour + réessai | dès 06:30 |
|
||||||
|
| `ecb_fx` | BCE USD/EUR | 1×/jour ouvré | lun-ven après 16:15 |
|
||||||
|
| `eu_bulletin` | Weekly Oil Bulletin (France TTC et HTT) | hebdomadaire | jeudi dès 13:00 |
|
||||||
|
| `dgec_monthly` | DGEC (Brent, marge, prix HTT/TTC) | contrôle quotidien, publication mensuelle | dès 07:00 |
|
||||||
|
| `portwatch` | IMF PortWatch (détroits) | 1×/jour, fenêtre glissante 12 jours | dès 08:00 |
|
||||||
|
| `news_geo` | actualités géopolitiques et logistiques | toutes les 2 heures | toujours |
|
||||||
|
| `promotions` | opérations commerciales des enseignes | 3×/jour | 07:30 – 21:30 |
|
||||||
|
|
||||||
|
Supervision : table `jobs` (source, fréquence, dernière exécution réussie, dernière observation
|
||||||
|
disponible, prochaine exécution, état, détail des échecs), `GET /api/jobs`, et fenêtre **Supervision**
|
||||||
|
dans l'interface. Inventaire en ligne de commande : `python3 scheduler.py --list`.
|
||||||
|
|
||||||
|
Constat mesuré : une extraction Ollama avec `mistral-small3.2:24b` prend environ 2 à 3 minutes par
|
||||||
|
article ; le nombre d'articles traités par passage est donc borné (`FUEL_NEWS_MAX_PER_RUN=3`,
|
||||||
|
`FUEL_PROMO_MAX_PER_RUN=3`). GDELT répond souvent 429 depuis la VM : les RSS Google News assurent
|
||||||
|
la couverture, GDELT reste un bonus.
|
||||||
|
|
||||||
|
### Prix locaux : horaire et sans doublon
|
||||||
|
|
||||||
|
Le flux instantané est récupéré chaque heure pour chaque zone favorite. Un **événement prix**
|
||||||
|
(`price_events`) n'est journalisé que si le prix **ou** l'horodatage publié par la station a changé ;
|
||||||
|
un prix identique ne crée donc aucune ligne. Lors d'une demande de conseil, le flux est actualisé de
|
||||||
|
force s'il a plus de 15 minutes (`FUEL_LOCAL_MAX_AGE`, 900 s par défaut).
|
||||||
|
|
||||||
|
### Métadonnées temporelles
|
||||||
|
|
||||||
|
Chaque donnée distingue :
|
||||||
|
|
||||||
|
- `observed_at` : date réelle de l'observation (ou date publiée par la station) ;
|
||||||
|
- `published_at` : date de publication par la source, quand elle existe ;
|
||||||
|
- `fetched_at` : date de notre téléchargement — **jamais** utilisée comme date d'observation.
|
||||||
|
|
||||||
|
Pour un événement futur : `valid_from` / `valid_until`. Les promotions conservent enseigne, zone,
|
||||||
|
carburants, nature, remise au litre, source et confiance ; « prix coûtant » n'est jamais traduit
|
||||||
|
en « moins cher » sans comparaison avec les autres stations.
|
||||||
|
|
||||||
## Collecte amont (séparée des favoris)
|
## Collecte amont (séparée des favoris)
|
||||||
|
|
||||||
`collector.py` exécute deux collectes indépendantes :
|
`collector.py` exécute deux collectes indépendantes :
|
||||||
|
|||||||
27
app.py
27
app.py
@@ -23,6 +23,8 @@ from xml.etree import ElementTree as ET
|
|||||||
import brands
|
import brands
|
||||||
import collector
|
import collector
|
||||||
import market
|
import market
|
||||||
|
import promotions
|
||||||
|
import scheduler
|
||||||
import storage
|
import storage
|
||||||
from decision import recommend
|
from decision import recommend
|
||||||
|
|
||||||
@@ -191,6 +193,12 @@ def geocode_address(query):
|
|||||||
|
|
||||||
|
|
||||||
def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None):
|
def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None):
|
||||||
|
# Flux instantané : actualisation forcée si le dernier téléchargement a plus de 15 minutes.
|
||||||
|
try:
|
||||||
|
refresh = collector.ensure_fresh_local(int(os.environ.get("FUEL_LOCAL_MAX_AGE", "900")))
|
||||||
|
except Exception as exc:
|
||||||
|
LOG.warning("Actualisation locale impossible : %s", type(exc).__name__)
|
||||||
|
refresh = dict(refreshed=False, error=type(exc).__name__)
|
||||||
stations, error = [], None
|
stations, error = [], None
|
||||||
try:
|
try:
|
||||||
stations = nearest_stations(lat, lon, fuel, radius_km)
|
stations = nearest_stations(lat, lon, fuel, radius_km)
|
||||||
@@ -241,6 +249,10 @@ def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None
|
|||||||
summary="Le choix de la station et le moment de ravitaillement sont évalués séparément.",
|
summary="Le choix de la station et le moment de ravitaillement sont évalués séparément.",
|
||||||
distance_note="Distances à vol d’oiseau, pas des trajets routiers. Le détour peut annuler l’économie.",
|
distance_note="Distances à vol d’oiseau, pas des trajets routiers. Le détour peut annuler l’économie.",
|
||||||
price_max_age_days=storage.MAX_PRICE_AGE_DAYS,
|
price_max_age_days=storage.MAX_PRICE_AGE_DAYS,
|
||||||
|
local_refresh=refresh,
|
||||||
|
promotions=promotions.active()[:12],
|
||||||
|
promotions_note="Une opération annoncée n’est pas forcément la moins chère : "
|
||||||
|
"comparez son tarif estimé aux autres stations du rayon.",
|
||||||
)
|
)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@@ -308,6 +320,21 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return self.send_json(dict(fuels=FUEL_TYPES, default_fuel=DEFAULT_FUEL))
|
return self.send_json(dict(fuels=FUEL_TYPES, default_fuel=DEFAULT_FUEL))
|
||||||
if path == "/api/status":
|
if path == "/api/status":
|
||||||
return self.send_json(collector.status())
|
return self.send_json(collector.status())
|
||||||
|
if path == "/api/jobs":
|
||||||
|
return self.send_json(
|
||||||
|
dict(
|
||||||
|
jobs=scheduler.inventory(),
|
||||||
|
note="Inventaire des collecteurs : source, fréquence, dernière exécution réussie, "
|
||||||
|
"dernière observation disponible, prochaine exécution et état.",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if path == "/api/promotions":
|
||||||
|
return self.send_json(
|
||||||
|
dict(
|
||||||
|
items=promotions.active()[:40],
|
||||||
|
note="Opérations annoncées ou en cours, avec leur source.",
|
||||||
|
)
|
||||||
|
)
|
||||||
if path == "/api/upstream":
|
if path == "/api/upstream":
|
||||||
return self.send_json(
|
return self.send_json(
|
||||||
dict(
|
dict(
|
||||||
|
|||||||
218
collector.py
218
collector.py
@@ -10,6 +10,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import fcntl
|
import fcntl
|
||||||
import json
|
import json
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
import storage
|
import storage
|
||||||
@@ -280,6 +282,222 @@ def collect(load=None, force=False):
|
|||||||
return dict(status=outcome, count=count, detail=detail, upstream=upstream_result)
|
return dict(status=outcome, count=count, detail=detail, upstream=upstream_result)
|
||||||
|
|
||||||
|
|
||||||
|
def _selected_stations(rows, favorites):
|
||||||
|
return [
|
||||||
|
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
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def job_local_prices(force=False, load=None):
|
||||||
|
"""Prix locaux : chaque heure pour chaque zone suivie, sans doublon à l'identique.
|
||||||
|
|
||||||
|
Un événement prix n'est journalisé que si le prix ou l'horodatage déclaré par la station
|
||||||
|
a changé ; l'instantané quotidien reste disponible pour les médianes et les tendances.
|
||||||
|
"""
|
||||||
|
favorites = storage.list_entities("favorites")
|
||||||
|
if not favorites:
|
||||||
|
return dict(status="unchanged", stored=0, detail="aucun favori suivi")
|
||||||
|
if load is None:
|
||||||
|
import app
|
||||||
|
|
||||||
|
def load():
|
||||||
|
return app.load_fuel_data(force=True)
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
rows = load()
|
||||||
|
selected = _selected_stations(rows, favorites)
|
||||||
|
if not selected:
|
||||||
|
return dict(status="unchanged", stored=0, detail="aucune station dans le rayon des favoris actuels")
|
||||||
|
storage.record_observations(selected, now)
|
||||||
|
storage.sync_station_names(rows, now)
|
||||||
|
events = storage.record_price_events(selected, now)
|
||||||
|
declared = [
|
||||||
|
row["updates"].get(fuel) for row in selected for fuel in row["prices"] if row["updates"].get(fuel)
|
||||||
|
]
|
||||||
|
return dict(
|
||||||
|
status="ok",
|
||||||
|
stored=events,
|
||||||
|
events=events,
|
||||||
|
stations=len(selected),
|
||||||
|
last_observation_at=max(declared) if declared else None,
|
||||||
|
detail=f"{len(selected)} stations comparées, {events} changement(s) de prix enregistré(s)",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_fresh_local(max_age_seconds=900):
|
||||||
|
"""Actualise le flux local s'il a plus de 10–15 minutes, sur demande de conseil."""
|
||||||
|
import app
|
||||||
|
|
||||||
|
cached = app.cache_get("fuel_data", ttl=10**9)
|
||||||
|
stamp = None
|
||||||
|
with sqlite3.connect(app.CACHE_DB, timeout=20) as db:
|
||||||
|
row = db.execute("SELECT ts FROM cache WHERE key='fuel_data'").fetchone()
|
||||||
|
stamp = row[0] if row else None
|
||||||
|
age = None if stamp is None else time.time() - stamp
|
||||||
|
if cached is not None and age is not None and age <= max_age_seconds:
|
||||||
|
return dict(refreshed=False, age_seconds=round(age, 1))
|
||||||
|
rows = app.load_fuel_data(force=True)
|
||||||
|
storage.sync_station_names(rows)
|
||||||
|
return dict(refreshed=True, age_seconds=None if age is None else round(age, 1), stations=len(rows))
|
||||||
|
|
||||||
|
|
||||||
|
def _delta_series(name, rows):
|
||||||
|
"""Nombre de valeurs réellement nouvelles pour une série (détection de nouvelle période)."""
|
||||||
|
known = {row["day"] for row in storage.upstream_series(name)}
|
||||||
|
return [row for row in rows if row["day"] not in known]
|
||||||
|
|
||||||
|
|
||||||
|
def job_dgec_monthly(force=False):
|
||||||
|
"""DGEC : Brent, marge de raffinage, prix HTT/TTC — contrôle quotidien, publication mensuelle."""
|
||||||
|
urls = upstream.dgec_urls()
|
||||||
|
stored, newest, unchanged = 0, None, True
|
||||||
|
brent = upstream.parse_dgec_brent(upstream.fetch_bytes(urls["brent"], 90))
|
||||||
|
if _delta_series("dgec_brent_usd", brent):
|
||||||
|
unchanged = False
|
||||||
|
stored += storage.save_upstream("dgec_brent_usd", brent, "USD/baril", DGEC_SOURCE)
|
||||||
|
margin = upstream.parse_dgec_margin(upstream.fetch_bytes(urls["margin"], 90))
|
||||||
|
stored += storage.save_upstream(
|
||||||
|
"dgec_margin_usd_per_bbl",
|
||||||
|
[dict(day=row["day"], value=row["usd_per_bbl"]) for row in margin],
|
||||||
|
"USD/baril",
|
||||||
|
DGEC_SOURCE,
|
||||||
|
)
|
||||||
|
stored += storage.save_upstream(
|
||||||
|
"dgec_margin_eur_per_tonne",
|
||||||
|
[dict(day=row["day"], value=row["eur_per_tonne"]) for row in margin],
|
||||||
|
"EUR/tonne",
|
||||||
|
DGEC_SOURCE,
|
||||||
|
)
|
||||||
|
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 and _delta_series(f"fr_htt_{fuel}", htt):
|
||||||
|
unchanged = False
|
||||||
|
if htt:
|
||||||
|
stored += storage.save_upstream(f"fr_htt_{fuel}", htt, "EUR/L", f"{DGEC_SOURCE} – hors taxes")
|
||||||
|
if ttc:
|
||||||
|
stored += storage.save_upstream(f"fr_ttc_{fuel}", ttc, "EUR/L", f"{DGEC_SOURCE} – TTC")
|
||||||
|
newest = max([row["day"] for row in prices] or [row["day"] for row in brent] or [None])
|
||||||
|
return dict(
|
||||||
|
status="unchanged" if unchanged else "ok",
|
||||||
|
stored=stored,
|
||||||
|
last_observation_at=newest,
|
||||||
|
month=newest,
|
||||||
|
detail=("période déjà connue" if unchanged else "nouvelle période DGEC enregistrée"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def job_eu_bulletin(force=False):
|
||||||
|
"""Bulletin pétrolier européen : publication hebdomadaire du jeudi."""
|
||||||
|
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")
|
||||||
|
stored = 0
|
||||||
|
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:
|
||||||
|
stored += storage.save_upstream(f"eu_fr_{product}_ttc", ttc, "EUR/L", f"{EU_SOURCE} – TTC")
|
||||||
|
if htt:
|
||||||
|
stored += storage.save_upstream(f"eu_fr_{product}_htt", htt, "EUR/L", f"{EU_SOURCE} – hors taxes")
|
||||||
|
newest = max(row["day"] for row in with_ttc)
|
||||||
|
return dict(
|
||||||
|
status="ok", stored=stored, last_observation_at=newest, detail=f"semaine du {newest} enregistrée"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def job_market_daily(force=False):
|
||||||
|
"""Cotation quotidienne du Brent (Stooq, puis page publique ; clé EIA si fournie)."""
|
||||||
|
import market
|
||||||
|
|
||||||
|
quote = market.fetch(force=True)
|
||||||
|
if quote.get("price_usd") is None or not quote.get("date"):
|
||||||
|
return dict(status="error", stored=0, detail=quote.get("summary", "cotation indisponible")[:200])
|
||||||
|
rows = [
|
||||||
|
dict(
|
||||||
|
day=quote["date"], value=quote["price_usd"], observed_at=quote["date"], published_at=quote["date"]
|
||||||
|
)
|
||||||
|
]
|
||||||
|
stored = storage.save_upstream("brent_usd_daily", rows, "USD/baril", quote.get("source") or MARKET_SOURCE)
|
||||||
|
if quote.get("price_eur"):
|
||||||
|
stored += storage.save_upstream(
|
||||||
|
"brent_eur_daily",
|
||||||
|
[dict(rows[0], value=quote["price_eur"])],
|
||||||
|
"EUR/baril",
|
||||||
|
quote.get("source") or MARKET_SOURCE,
|
||||||
|
)
|
||||||
|
return dict(
|
||||||
|
status="ok",
|
||||||
|
stored=stored,
|
||||||
|
last_observation_at=quote["date"],
|
||||||
|
trend=quote.get("trend"),
|
||||||
|
detail=quote.get("summary", "")[:200],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def job_ecb_fx(force=False):
|
||||||
|
"""Taux BCE USD/EUR : jours ouvrés, après la publication de 16 h."""
|
||||||
|
import market
|
||||||
|
|
||||||
|
series = market.ecb_rate_series()
|
||||||
|
stored = storage.save_upstream(
|
||||||
|
"usd_per_eur",
|
||||||
|
[
|
||||||
|
dict(day=row["day"], value=row["value"], observed_at=row["day"], published_at=row["day"])
|
||||||
|
for row in series
|
||||||
|
],
|
||||||
|
"USD/EUR",
|
||||||
|
"BCE (quotidien, jours ouvrés)",
|
||||||
|
)
|
||||||
|
newest = max(row["day"] for row in series)
|
||||||
|
return dict(
|
||||||
|
status="ok", stored=stored, last_observation_at=newest, detail=f"taux de référence BCE du {newest}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def job_portwatch(force=False):
|
||||||
|
"""Détroits : collecte quotidienne avec fenêtre glissante pour les révisions."""
|
||||||
|
pairs = upstream.fetch_chokepoint_window(12)
|
||||||
|
stored = storage.save_chokepoints(pairs, PORTWATCH_SOURCE)
|
||||||
|
newest = max(entry["day"] for _name, entry in pairs)
|
||||||
|
return dict(
|
||||||
|
status="ok",
|
||||||
|
stored=stored,
|
||||||
|
chokepoints=len({name for name, _ in pairs}),
|
||||||
|
last_observation_at=newest,
|
||||||
|
detail=f"fenêtre de 12 jours, dernière observation {newest}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def job_news_geo(force=False):
|
||||||
|
"""Actualités géopolitiques et logistiques : contrôle toutes les 2 heures."""
|
||||||
|
import news
|
||||||
|
|
||||||
|
outcome = news.collect(force=force)
|
||||||
|
outcome.setdefault("stored", outcome.get("events", 0))
|
||||||
|
return outcome
|
||||||
|
|
||||||
|
|
||||||
|
def job_promotions(force=False):
|
||||||
|
"""Opérations commerciales : plusieurs contrôles par jour."""
|
||||||
|
import promotions
|
||||||
|
|
||||||
|
outcome = promotions.collect(force=force)
|
||||||
|
outcome.setdefault("stored", outcome.get("promotions", 0))
|
||||||
|
return outcome
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<html lang="fr">
|
<html lang="fr">
|
||||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Conseiller carburant</title><link rel="stylesheet" href="/style.css"><script defer src="/ui.js"></script></head>
|
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Conseiller carburant</title><link rel="stylesheet" href="/style.css"><script defer src="/ui.js"></script></head>
|
||||||
<body><main>
|
<body><main>
|
||||||
<header><div><div class="eyebrow">Cortex Lab · Mobilité</div><h1>Le bon arrêt.<br><span>Au bon moment.</span></h1></div><div class="header-actions"><button class="secondary" id="manage-vehicles">Mes véhicules</button><button class="secondary" id="manage-favorites">Mes favoris</button></div></header>
|
<header><div><div class="eyebrow">Cortex Lab · Mobilité</div><h1>Le bon arrêt.<br><span>Au bon moment.</span></h1></div><div class="header-actions"><button class="secondary" id="manage-vehicles">Mes véhicules</button><button class="secondary" id="manage-favorites">Mes favoris</button><button class="secondary" id="diagnostic">Supervision</button></div></header>
|
||||||
<div class="layout"><aside>
|
<div class="layout"><aside>
|
||||||
<section class="card"><h2>Votre prochain plein</h2>
|
<section class="card"><h2>Votre prochain plein</h2>
|
||||||
<label for="vehicle">Véhicule</label><select id="vehicle"><option value="">Comparer seulement les stations</option></select><p id="vehicle-info" class="hint">Ajoutez un véhicule pour adapter le conseil à votre autonomie.</p>
|
<label for="vehicle">Véhicule</label><select id="vehicle"><option value="">Comparer seulement les stations</option></select><p id="vehicle-info" class="hint">Ajoutez un véhicule pour adapter le conseil à votre autonomie.</p>
|
||||||
@@ -22,5 +22,6 @@
|
|||||||
<dialog id="vehicles-dialog"><div class="dialog-head"><h2>Mes véhicules</h2><button class="close secondary" data-close="vehicles-dialog" aria-label="Fermer">×</button></div><div id="vehicles-list" class="items"></div><button id="new-vehicle" class="secondary">+ Nouveau véhicule</button>
|
<dialog id="vehicles-dialog"><div class="dialog-head"><h2>Mes véhicules</h2><button class="close secondary" data-close="vehicles-dialog" aria-label="Fermer">×</button></div><div id="vehicles-list" class="items"></div><button id="new-vehicle" class="secondary">+ Nouveau véhicule</button>
|
||||||
<form id="vehicle-form"><h3 id="vehicle-form-title">Ajouter un véhicule</h3><input name="id" type="hidden"><label>Nom<input name="name" required maxlength="80" placeholder="Voiture, van aménagé…"></label><div class="two"><label>Carburant<select name="fuel" id="vehicle-fuel"></select></label><label>Consommation (L/100 km)<input name="consumption" type="number" min="0.1" max="60" step="0.1" required></label></div><label>Marge minimale à conserver (km)<input name="min_range_km" type="number" min="0" max="1500" step="1" value="80" required></label><p class="hint">Le conseil n’encouragera pas à entamer cette marge pour attendre une baisse.</p><label>Usage<select name="usage"><option value="regular">Régulier</option><option value="occasional">Occasionnel / van</option></select></label><div class="two"><label id="monthly-field">Kilomètres par mois<input name="monthly_km" type="number" min="1" max="30000" value="1000" required></label><label>Réservoir (L, facultatif)<input name="tank_liters" type="number" min="1" max="300" step="0.1"></label></div><button class="primary" type="submit">Enregistrer le véhicule</button><p class="form-error" role="alert"></p></form></dialog>
|
<form id="vehicle-form"><h3 id="vehicle-form-title">Ajouter un véhicule</h3><input name="id" type="hidden"><label>Nom<input name="name" required maxlength="80" placeholder="Voiture, van aménagé…"></label><div class="two"><label>Carburant<select name="fuel" id="vehicle-fuel"></select></label><label>Consommation (L/100 km)<input name="consumption" type="number" min="0.1" max="60" step="0.1" required></label></div><label>Marge minimale à conserver (km)<input name="min_range_km" type="number" min="0" max="1500" step="1" value="80" required></label><p class="hint">Le conseil n’encouragera pas à entamer cette marge pour attendre une baisse.</p><label>Usage<select name="usage"><option value="regular">Régulier</option><option value="occasional">Occasionnel / van</option></select></label><div class="two"><label id="monthly-field">Kilomètres par mois<input name="monthly_km" type="number" min="1" max="30000" value="1000" required></label><label>Réservoir (L, facultatif)<input name="tank_liters" type="number" min="1" max="300" step="0.1"></label></div><button class="primary" type="submit">Enregistrer le véhicule</button><p class="form-error" role="alert"></p></form></dialog>
|
||||||
<dialog id="favorites-dialog"><div class="dialog-head"><h2>Mes favoris</h2><button class="close secondary" data-close="favorites-dialog" aria-label="Fermer">×</button></div><div id="favorites-list" class="items"></div><p class="hint">Pour un nouveau lieu, recherchez une adresse sur la page puis choisissez « Enregistrer ce lieu ».</p><form id="favorite-form"><h3>Enregistrer le lieu</h3><input name="id" type="hidden"><label>Nom<input name="name" required maxlength="80" placeholder="Maison, travail, vacances…"></label><div class="two"><label>Latitude<input name="lat" type="number" min="-90" max="90" step="any" required></label><label>Longitude<input name="lon" type="number" min="-180" max="180" step="any" required></label></div><label>Rayon (km)<input name="radius_km" type="number" min="1" max="80" value="15" required></label><button class="primary" type="submit">Enregistrer le favori</button><p class="form-error" role="alert"></p></form></dialog>
|
<dialog id="favorites-dialog"><div class="dialog-head"><h2>Mes favoris</h2><button class="close secondary" data-close="favorites-dialog" aria-label="Fermer">×</button></div><div id="favorites-list" class="items"></div><p class="hint">Pour un nouveau lieu, recherchez une adresse sur la page puis choisissez « Enregistrer ce lieu ».</p><form id="favorite-form"><h3>Enregistrer le lieu</h3><input name="id" type="hidden"><label>Nom<input name="name" required maxlength="80" placeholder="Maison, travail, vacances…"></label><div class="two"><label>Latitude<input name="lat" type="number" min="-90" max="90" step="any" required></label><label>Longitude<input name="lon" type="number" min="-180" max="180" step="any" required></label></div><label>Rayon (km)<input name="radius_km" type="number" min="1" max="80" value="15" required></label><button class="primary" type="submit">Enregistrer le favori</button><p class="form-error" role="alert"></p></form></dialog>
|
||||||
|
<dialog id="jobs-dialog"><div class="dialog-head"><h2>Supervision des collecteurs</h2><button class="close secondary" data-close="jobs-dialog" aria-label="Fermer">×</button></div><p class="hint">Chaque source a sa propre temporalité. « Prochaine exécution » tient compte de la fenêtre autorisée (jours ouvrés, jeudi, etc.).</p><div id="jobs-list" class="items">Chargement…</div><button class="secondary" id="jobs-refresh">Actualiser</button></dialog>
|
||||||
<dialog id="range-dialog"><div class="dialog-head"><h2>Autonomie restante</h2><button class="close secondary" data-close="range-dialog" aria-label="Fermer">×</button></div><form id="range-form"><p id="range-vehicle" class="hint"></p><label for="remaining-km">Quelle autonomie affiche le véhicule ? (km)</label><input id="remaining-km" name="remaining_km" type="number" min="0" max="5000" step="1" required autocomplete="off"><p class="hint">Saisissez l’autonomie totale affichée. Votre marge sera déduite automatiquement. Cette valeur ne sera pas enregistrée.</p><div id="trip-fields" hidden><label>Prochain trajet<select id="trip-mode"><option value="none">Aucun trajet prévu</option><option value="planned">Un trajet est prévu</option></select></label><div id="trip-details" hidden><label>Date du départ<input name="trip_date" type="date"></label><label>Distance totale (km, retour compris si prévu)<input name="trip_km" type="number" min="1" max="20000" step="1"></label></div></div><button type="submit" class="primary wide">Calculer avec cette autonomie</button><p class="form-error" role="alert"></p></form></dialog>
|
<dialog id="range-dialog"><div class="dialog-head"><h2>Autonomie restante</h2><button class="close secondary" data-close="range-dialog" aria-label="Fermer">×</button></div><form id="range-form"><p id="range-vehicle" class="hint"></p><label for="remaining-km">Quelle autonomie affiche le véhicule ? (km)</label><input id="remaining-km" name="remaining_km" type="number" min="0" max="5000" step="1" required autocomplete="off"><p class="hint">Saisissez l’autonomie totale affichée. Votre marge sera déduite automatiquement. Cette valeur ne sera pas enregistrée.</p><div id="trip-fields" hidden><label>Prochain trajet<select id="trip-mode"><option value="none">Aucun trajet prévu</option><option value="planned">Un trajet est prévu</option></select></label><div id="trip-details" hidden><label>Date du départ<input name="trip_date" type="date"></label><label>Distance totale (km, retour compris si prévu)<input name="trip_km" type="number" min="1" max="20000" step="1"></label></div></div><button type="submit" class="primary wide">Calculer avec cette autonomie</button><p class="form-error" role="alert"></p></form></dialog>
|
||||||
</body></html>
|
</body></html>
|
||||||
|
|||||||
82
llm.py
Normal file
82
llm.py
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
"""Client Ollama minimal : extraction de données non structurées, jamais de décision.
|
||||||
|
|
||||||
|
Le modèle ne fait que transformer un texte en JSON validé. Aucun signal n'est accepté
|
||||||
|
sans source : les champs ``source_url`` et la date d'observation restent obligatoires côté
|
||||||
|
appelant, et le modèle ne décide jamais du conseil carburant.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://10.53.2.22:11434").rstrip("/")
|
||||||
|
PRIMARY_MODEL = os.environ.get("OLLAMA_MODEL", "mistral-small3.2:24b")
|
||||||
|
FALLBACK_MODEL = os.environ.get("OLLAMA_FALLBACK_MODEL", "gemma4:12b")
|
||||||
|
TIMEOUT = int(os.environ.get("OLLAMA_TIMEOUT", "180"))
|
||||||
|
MAX_PROMPT_CHARS = 6000
|
||||||
|
|
||||||
|
|
||||||
|
def available(timeout=8):
|
||||||
|
"""Liste les modèles réellement disponibles sur le serveur Ollama."""
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"{OLLAMA_URL}/api/tags", timeout=timeout) as response:
|
||||||
|
return [model["name"] for model in json.loads(response.read()).get("models", [])]
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def parse_json(text):
|
||||||
|
"""Extrait un objet JSON d'une réponse de modèle, même entourée de texte."""
|
||||||
|
if not text:
|
||||||
|
raise ValueError("réponse vide")
|
||||||
|
cleaned = text.strip()
|
||||||
|
cleaned = re.sub(r"^```(?:json)?|```$", "", cleaned, flags=re.M).strip()
|
||||||
|
try:
|
||||||
|
data = json.loads(cleaned)
|
||||||
|
except ValueError:
|
||||||
|
match = re.search(r"\{.*\}", cleaned, re.S)
|
||||||
|
if not match:
|
||||||
|
raise ValueError("aucun objet JSON") from None
|
||||||
|
data = json.loads(match.group(0))
|
||||||
|
if isinstance(data, list):
|
||||||
|
return data
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise ValueError("objet JSON attendu")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def generate(prompt, model=None, timeout=None, temperature=0):
|
||||||
|
"""Appel unique à Ollama ; lève en cas d'échec réseau ou de réponse illisible."""
|
||||||
|
payload = json.dumps(
|
||||||
|
{
|
||||||
|
"model": model or PRIMARY_MODEL,
|
||||||
|
"prompt": prompt[:MAX_PROMPT_CHARS],
|
||||||
|
"stream": False,
|
||||||
|
"format": "json",
|
||||||
|
"options": {"temperature": temperature, "num_predict": 700},
|
||||||
|
}
|
||||||
|
).encode()
|
||||||
|
request = urllib.request.Request(
|
||||||
|
urllib.parse.urljoin(OLLAMA_URL + "/", "api/generate"),
|
||||||
|
data=payload,
|
||||||
|
headers={"Content-Type": "application/json", "User-Agent": "CortexFuelAdvisor/0.4"},
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(request, timeout=timeout or TIMEOUT) as response:
|
||||||
|
body = json.loads(response.read().decode("utf-8", "replace"))
|
||||||
|
text = str(body.get("response", "")).strip()
|
||||||
|
return parse_json(text), body.get("model") or model or PRIMARY_MODEL
|
||||||
|
|
||||||
|
|
||||||
|
def extract(prompt, models=None, timeout=None):
|
||||||
|
"""Essaie le modèle principal puis le repli. Retourne (données, modèle utilisé)."""
|
||||||
|
errors = []
|
||||||
|
for model in models or (PRIMARY_MODEL, FALLBACK_MODEL):
|
||||||
|
try:
|
||||||
|
return generate(prompt, model=model, timeout=timeout)
|
||||||
|
except Exception as exc:
|
||||||
|
errors.append(f"{model}: {type(exc).__name__}")
|
||||||
|
raise RuntimeError("Ollama indisponible (" + ", ".join(errors) + ")")
|
||||||
17
market.py
17
market.py
@@ -152,6 +152,23 @@ def provider_page():
|
|||||||
PROVIDERS = {"stooq": provider_stooq, "page": provider_page}
|
PROVIDERS = {"stooq": provider_stooq, "page": provider_page}
|
||||||
|
|
||||||
|
|
||||||
|
def ecb_rate_series():
|
||||||
|
"""Taux USD/EUR de la BCE avec leur date de référence (observed_at = jour de cotation)."""
|
||||||
|
text = fetch_bytes(ECB_URL, 15).decode("utf-8", "replace")
|
||||||
|
out = []
|
||||||
|
for line in text.splitlines()[1:]:
|
||||||
|
parts = line.split(",")
|
||||||
|
if len(parts) < 9 or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", parts[6].strip('"')):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
out.append(dict(day=parts[6].strip('"'), value=_number(parts[7], "taux de change")))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if not out:
|
||||||
|
raise ValueError("série BCE illisible")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def ecb_usd_per_eur():
|
def ecb_usd_per_eur():
|
||||||
"""Taux USD par euro publié par la BCE (cache 24 h). Retourne None si indisponible."""
|
"""Taux USD par euro publié par la BCE (cache 24 h). Retourne None si indisponible."""
|
||||||
cached = cache_get("fx", 86400)
|
cached = cache_get("fx", 86400)
|
||||||
|
|||||||
246
news.py
Normal file
246
news.py
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
"""Actualités géopolitiques et logistiques : détection de nouveaux articles, extraction structurée.
|
||||||
|
|
||||||
|
Le programme récupère lui-même les articles (RSS Google News, GDELT en secours), ne relance
|
||||||
|
l'extraction Ollama que pour un **nouvel** article jamais analysé, et exige une source.
|
||||||
|
Aucune règle n'est inventée : un article sans URL ou sans date n'est pas transformé en signal.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import html
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from xml.etree import ElementTree as ET
|
||||||
|
|
||||||
|
import llm
|
||||||
|
import storage
|
||||||
|
import upstream
|
||||||
|
|
||||||
|
USER_AGENT = upstream.USER_AGENT
|
||||||
|
MAX_ARTICLES_PER_RUN = int(os.environ.get("FUEL_NEWS_MAX_PER_RUN", "3"))
|
||||||
|
|
||||||
|
TOPICS = {
|
||||||
|
"ormuz": ["détroit Ormuz pétrole", "Strait of Hormuz oil tanker"],
|
||||||
|
"suez_babelmandeb": ["Bab el-Mandeb Suez pétrole", "mer Rouge pétrolier attaque"],
|
||||||
|
"opep": ["OPEP+ décision production pétrole", "OPEC+ quota oil output"],
|
||||||
|
"sanctions": ["sanctions pétrole Russie Iran", "oil sanctions export"],
|
||||||
|
"raffineries": ["raffinerie arrêt incident", "refinery outage fire"],
|
||||||
|
"depots_greves": ["grève dépôt carburant", "blocage raffinerie France carburant"],
|
||||||
|
"fiscalite": ["taxe carburant accise France", "fiscalité carburant augmentation"],
|
||||||
|
}
|
||||||
|
|
||||||
|
PROMPT = """Tu analyses un article de presse pour un outil interne d'analyse des prix des carburants.
|
||||||
|
Réponds UNIQUEMENT par un objet JSON, sans texte autour, au format :
|
||||||
|
{{"pertinent": true|false, "evenements": [{{"type": "chokepoint|offre|raffinage|logistique|sanctions|fiscalite|autre",
|
||||||
|
"direction": "hausse|baisse|incertaine", "magnitude": "faible|moyenne|forte|inconnue",
|
||||||
|
"carburants": ["gazole","sp95","e10","sp98","e85","gplc"] ou [], "zone": "lieu ou région en clair",
|
||||||
|
"horizon_jours": entier ou null, "confiance": nombre entre 0 et 1,
|
||||||
|
"debut": "AAAA-MM-JJ" ou null, "fin": "AAAA-MM-JJ" ou null}}]}}
|
||||||
|
Règles strictes : n'invente rien. Si l'article ne concerne pas l'approvisionnement, la logistique,
|
||||||
|
la production, les sanctions ou la fiscalité des carburants, mets "pertinent": false et une liste vide.
|
||||||
|
La direction décrit l'effet probable sur les prix, "incertaine" si ce n'est pas clair.
|
||||||
|
horizon_jours est la durée estimée de l'effet en jours, null si inconnue. Ne dépasse jamais 60.
|
||||||
|
|
||||||
|
Titre : {title}
|
||||||
|
Source : {source}
|
||||||
|
Date de publication : {published}
|
||||||
|
Texte : {text}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def article_hash(url):
|
||||||
|
return hashlib.sha256(str(url).strip().encode("utf-8", "replace")).hexdigest()[:32]
|
||||||
|
|
||||||
|
|
||||||
|
def strip_html(text):
|
||||||
|
text = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", text or "", flags=re.S | re.I)
|
||||||
|
text = re.sub(r"<[^>]+>", " ", text)
|
||||||
|
return re.sub(r"\s+", " ", html.unescape(text)).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_rss(xml, source_label, topic):
|
||||||
|
"""Articles d'un flux RSS, avec date de publication quand elle est fournie."""
|
||||||
|
articles = []
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(xml)
|
||||||
|
except ET.ParseError:
|
||||||
|
return articles
|
||||||
|
for item in root.findall(".//item"):
|
||||||
|
link = (item.findtext("link") or "").strip()
|
||||||
|
title = strip_html(item.findtext("title") or "")
|
||||||
|
if not link or not title:
|
||||||
|
continue
|
||||||
|
published = parse_rss_date(item.findtext("pubDate") or "")
|
||||||
|
articles.append(
|
||||||
|
dict(
|
||||||
|
hash=article_hash(link),
|
||||||
|
url=link,
|
||||||
|
title=title[:300],
|
||||||
|
source=strip_html(item.findtext("source") or source_label)[:80],
|
||||||
|
topic=topic,
|
||||||
|
published_at=published,
|
||||||
|
observed_at=published,
|
||||||
|
summary=strip_html(item.findtext("description") or "")[:600],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return articles
|
||||||
|
|
||||||
|
|
||||||
|
def parse_rss_date(text):
|
||||||
|
for pattern in ("%a, %d %b %Y %H:%M:%S %z", "%a, %d %b %Y %H:%M:%S %Z", "%Y-%m-%dT%H:%M:%SZ"):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text.strip(), pattern).astimezone(timezone.utc).date().isoformat()
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def google_news(query, topic, timeout=20):
|
||||||
|
url = "https://news.google.com/rss/search?q=" + urllib.parse.quote(query) + "&hl=fr&gl=FR&ceid=FR:fr"
|
||||||
|
return parse_rss(upstream.fetch_bytes(url, timeout, 4_000_000), "Google News", topic)
|
||||||
|
|
||||||
|
|
||||||
|
def gdelt(query, topic, timeout=30):
|
||||||
|
"""Secours : GDELT répond de façon intermittente (429 tolérés)."""
|
||||||
|
url = (
|
||||||
|
"https://api.gdeltproject.org/api/v2/doc/doc?query="
|
||||||
|
+ urllib.parse.quote(query)
|
||||||
|
+ "&mode=artlist&maxrecords=10&format=json&sort=datedesc"
|
||||||
|
)
|
||||||
|
payload = upstream.fetch_bytes(url, timeout, 2_000_000)
|
||||||
|
try:
|
||||||
|
rows = json.loads(payload).get("articles", [])
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
return []
|
||||||
|
articles = []
|
||||||
|
for row in rows:
|
||||||
|
link, title = str(row.get("url") or "").strip(), strip_html(str(row.get("title") or ""))
|
||||||
|
if not link or not title:
|
||||||
|
continue
|
||||||
|
day = None
|
||||||
|
stamp = str(row.get("seendate") or "")
|
||||||
|
if len(stamp) >= 8 and stamp[:8].isdigit():
|
||||||
|
day = f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]}"
|
||||||
|
articles.append(
|
||||||
|
dict(
|
||||||
|
hash=article_hash(link),
|
||||||
|
url=link,
|
||||||
|
title=title[:300],
|
||||||
|
source=str(row.get("domain") or "GDELT")[:80],
|
||||||
|
topic=topic,
|
||||||
|
published_at=day,
|
||||||
|
observed_at=day,
|
||||||
|
summary="",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return articles
|
||||||
|
|
||||||
|
|
||||||
|
def gather(topic_queries=None, use_gdelt=True):
|
||||||
|
"""Récupère les articles de tous les sujets ; lève si aucune source ne répond."""
|
||||||
|
topic_queries = topic_queries or TOPICS
|
||||||
|
articles, errors = [], []
|
||||||
|
for topic, queries in topic_queries.items():
|
||||||
|
for query in queries:
|
||||||
|
try:
|
||||||
|
articles.extend(google_news(query, topic))
|
||||||
|
except Exception as exc:
|
||||||
|
errors.append(f"rss {topic}: {type(exc).__name__}")
|
||||||
|
if use_gdelt:
|
||||||
|
try:
|
||||||
|
articles.extend(gdelt(queries[0], topic))
|
||||||
|
except Exception as exc:
|
||||||
|
errors.append(f"gdelt {topic}: {type(exc).__name__}")
|
||||||
|
if not articles and errors:
|
||||||
|
raise RuntimeError("aucune source d’actualités joignable (" + ", ".join(errors[:4]) + ")")
|
||||||
|
unique = {article["hash"]: article for article in articles}
|
||||||
|
return list(unique.values()), errors
|
||||||
|
|
||||||
|
|
||||||
|
def analyse(article, topic, models=None):
|
||||||
|
"""Extraction Ollama : renvoie la liste d'événements structurés, jamais une décision."""
|
||||||
|
prompt = PROMPT.format(
|
||||||
|
title=article["title"],
|
||||||
|
source=article.get("source", ""),
|
||||||
|
published=article.get("published_at") or "inconnue",
|
||||||
|
text=(article.get("summary") or article["title"])[:2500],
|
||||||
|
)
|
||||||
|
data, model = llm.extract(prompt, models=models)
|
||||||
|
if not data.get("pertinent"):
|
||||||
|
return [], model
|
||||||
|
observed = article.get("published_at") or article.get("observed_at")
|
||||||
|
events = []
|
||||||
|
for raw in (data.get("evenements") or [])[:5]:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
direction = str(raw.get("direction") or "incertaine").lower()
|
||||||
|
if direction not in ("hausse", "baisse", "incertaine"):
|
||||||
|
direction = "incertaine"
|
||||||
|
horizon = raw.get("horizon_jours")
|
||||||
|
try:
|
||||||
|
horizon = max(0, min(60, int(horizon))) if horizon is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
horizon = None
|
||||||
|
try:
|
||||||
|
confidence = max(0.0, min(1.0, float(raw.get("confiance"))))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
confidence = None
|
||||||
|
end = raw.get("fin")
|
||||||
|
if not end and observed and horizon:
|
||||||
|
end = (date.fromisoformat(observed) + timedelta(days=horizon)).isoformat()
|
||||||
|
events.append(
|
||||||
|
dict(
|
||||||
|
url_hash=article["hash"],
|
||||||
|
topic=topic,
|
||||||
|
event_type=str(raw.get("type") or "autre")[:40],
|
||||||
|
direction=direction,
|
||||||
|
magnitude=str(raw.get("magnitude") or "inconnue")[:20],
|
||||||
|
fuels=[str(f)[:10] for f in (raw.get("carburants") or []) if isinstance(f, (str, int))][:6],
|
||||||
|
zone=str(raw.get("zone") or "")[:80],
|
||||||
|
horizon_days=horizon,
|
||||||
|
confidence=confidence,
|
||||||
|
valid_from=raw.get("debut") or observed,
|
||||||
|
valid_until=end,
|
||||||
|
observed_at=observed,
|
||||||
|
published_at=article.get("published_at"),
|
||||||
|
source_url=article["url"],
|
||||||
|
extracted_by=model,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return events, model
|
||||||
|
|
||||||
|
|
||||||
|
def collect(topic_queries=None, models=None, force=False, limit=None):
|
||||||
|
"""Contrôle les actualités et n'appelle Ollama que sur des articles jamais analysés."""
|
||||||
|
articles, errors = gather(topic_queries)
|
||||||
|
fresh = storage.save_articles(articles, "geo")
|
||||||
|
limit = limit or MAX_ARTICLES_PER_RUN
|
||||||
|
todo = [article for article in fresh if article.get("topic")][:limit]
|
||||||
|
events, analysed = 0, []
|
||||||
|
for article in todo:
|
||||||
|
try:
|
||||||
|
found, _model = analyse(article, article["topic"], models=models)
|
||||||
|
except Exception as exc:
|
||||||
|
errors.append(f"ollama {article['hash'][:6]}: {type(exc).__name__}")
|
||||||
|
continue
|
||||||
|
for event in found:
|
||||||
|
storage.save_news_event(event)
|
||||||
|
events += 1
|
||||||
|
analysed.append(article["hash"])
|
||||||
|
storage.mark_analysed(analysed)
|
||||||
|
newest = max([article.get("published_at") or "" for article in articles] or [""])
|
||||||
|
return dict(
|
||||||
|
status="ok" if articles else "error",
|
||||||
|
articles=len(articles),
|
||||||
|
new=len(todo),
|
||||||
|
analysed=len(analysed),
|
||||||
|
events=events,
|
||||||
|
errors=errors[:6],
|
||||||
|
last_observation_at=newest or None,
|
||||||
|
detail="; ".join(errors[:3]) if errors else f"{len(analysed)} article(s) analysé(s)",
|
||||||
|
)
|
||||||
185
promotions.py
Normal file
185
promotions.py
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
"""Opérations commerciales carburant : recherche multi-sources et extraction structurée.
|
||||||
|
|
||||||
|
Les annonces sont récupérées par le programme (actualités et pages publiques des enseignes),
|
||||||
|
puis structurées par Ollama. Une annonce sans source vérifiable n'est jamais enregistrée.
|
||||||
|
« Prix coûtant » n'implique pas « moins cher » : la comparaison avec les autres stations
|
||||||
|
est faite séparément, par le moteur de décision.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import llm
|
||||||
|
import news
|
||||||
|
import storage
|
||||||
|
|
||||||
|
MAX_ITEMS_PER_BRAND = int(os.environ.get("FUEL_PROMO_MAX_PER_BRAND", "4"))
|
||||||
|
|
||||||
|
BRANDS = (
|
||||||
|
"E.Leclerc",
|
||||||
|
"Carrefour",
|
||||||
|
"Intermarché",
|
||||||
|
"Auchan",
|
||||||
|
"Système U",
|
||||||
|
"Cora",
|
||||||
|
"TotalEnergies",
|
||||||
|
"Esso",
|
||||||
|
"BP",
|
||||||
|
"Avia",
|
||||||
|
"Netto",
|
||||||
|
)
|
||||||
|
|
||||||
|
BRAND_QUERIES = {
|
||||||
|
"E.Leclerc": ["E.Leclerc carburant prix coûtant", "Leclerc essence opération carburant"],
|
||||||
|
"Carrefour": ["Carrefour carburant prix coûtant", "Carrefour essence remise carburant"],
|
||||||
|
"Intermarché": ["Intermarché carburant prix coûtant", "Intermarché essence opération"],
|
||||||
|
"Auchan": ["Auchan carburant prix coûtant", "Auchan essence opération carburant"],
|
||||||
|
"Système U": ["Système U carburant prix coûtant", "U express essence remise"],
|
||||||
|
"Cora": ["Cora carburant prix coûtant"],
|
||||||
|
"TotalEnergies": ["TotalEnergies remise carburant", "TotalEnergies prix carburant opération"],
|
||||||
|
"Esso": ["Esso remise carburant"],
|
||||||
|
"BP": ["BP remise carburant"],
|
||||||
|
"Avia": ["Avia remise carburant"],
|
||||||
|
"Netto": ["Netto carburant prix coûtant"],
|
||||||
|
}
|
||||||
|
|
||||||
|
GENERIC_QUERIES = [
|
||||||
|
"prix coûtant carburant week-end",
|
||||||
|
"prix plafonné carburant",
|
||||||
|
"remise carburant",
|
||||||
|
"bon d’achat carburant hypermarché",
|
||||||
|
"opération carburant à prix coûtant",
|
||||||
|
]
|
||||||
|
|
||||||
|
NATURES = ("prix_coutant", "prix_plafonne", "remise_litre", "bon_achat", "carte_fidelite", "autre")
|
||||||
|
|
||||||
|
PROMPT = """Tu extrais des opérations commerciales sur les carburants depuis un texte de presse.
|
||||||
|
Réponds UNIQUEMENT par un objet JSON :
|
||||||
|
{{"operations": [{{"enseigne": "nom de l'enseigne", "nature": "prix_coutant|prix_plafonne|remise_litre|bon_achat|carte_fidelite|autre",
|
||||||
|
"remise_par_litre": nombre en euros ou null, "carburants": ["gazole","sp95","e10","sp98","e85","gplc"] ou [],
|
||||||
|
"zone": "zone ou liste de stations en clair ou vide", "debut": "AAAA-MM-JJ" ou null, "fin": "AAAA-MM-JJ" ou null,
|
||||||
|
"confiance": nombre entre 0 et 1}}]}}
|
||||||
|
Règles : n'invente aucune enseigne absente du texte, aucune date absente, aucun montant absent.
|
||||||
|
Si le texte ne décrit pas d'opération carburant en cours ou annoncée, renvoie une liste vide.
|
||||||
|
La confiance reflète la précision du texte (dates et périmètre explicites = élevée).
|
||||||
|
|
||||||
|
Titre : {title}
|
||||||
|
Source : {source}
|
||||||
|
Date : {published}
|
||||||
|
Texte : {text}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def gather(use_gdelt=True):
|
||||||
|
"""Récupère les articles liés aux opérations commerciales de chaque enseigne."""
|
||||||
|
queries = {brand: BRAND_QUERIES.get(brand, [f"{brand} carburant"]) for brand in BRANDS}
|
||||||
|
queries["_general"] = GENERIC_QUERIES
|
||||||
|
articles, errors = news.gather(queries, use_gdelt=use_gdelt)
|
||||||
|
return articles, errors
|
||||||
|
|
||||||
|
|
||||||
|
def analyse(article, models=None):
|
||||||
|
"""Extraction structurée d'une annonce : enseigne, nature, dates, périmètre, confiance."""
|
||||||
|
prompt = PROMPT.format(
|
||||||
|
title=article["title"],
|
||||||
|
source=article.get("source", ""),
|
||||||
|
published=article.get("published_at") or "inconnue",
|
||||||
|
text=(article.get("summary") or article["title"])[:2500],
|
||||||
|
)
|
||||||
|
data, model = llm.extract(prompt, models=models)
|
||||||
|
observed = article.get("published_at") or article.get("observed_at")
|
||||||
|
out = []
|
||||||
|
for raw in (data.get("operations") or [])[:4]:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
brand = str(raw.get("enseigne") or "").strip()[:60]
|
||||||
|
nature = str(raw.get("nature") or "autre").strip().lower()
|
||||||
|
if not brand or nature not in NATURES:
|
||||||
|
continue
|
||||||
|
if (
|
||||||
|
brand.lower() not in article["title"].lower()
|
||||||
|
and brand.lower() not in (article.get("summary") or "").lower()
|
||||||
|
):
|
||||||
|
# Défense simple contre une enseigne inventée par le modèle.
|
||||||
|
continue
|
||||||
|
discount = raw.get("remise_par_litre")
|
||||||
|
try:
|
||||||
|
discount = round(float(discount), 3) if discount is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
discount = None
|
||||||
|
try:
|
||||||
|
confidence = max(0.0, min(1.0, float(raw.get("confiance"))))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
confidence = None
|
||||||
|
valid_from = raw.get("debut") or observed
|
||||||
|
out.append(
|
||||||
|
dict(
|
||||||
|
brand=brand,
|
||||||
|
nature=nature,
|
||||||
|
discount_per_liter=discount,
|
||||||
|
fuels=[str(f)[:10] for f in (raw.get("carburants") or []) if isinstance(f, (str, int))][:6],
|
||||||
|
scope=article.get("topic") or "",
|
||||||
|
stations=str(raw.get("zone") or "")[:200],
|
||||||
|
valid_from=valid_from,
|
||||||
|
valid_until=raw.get("fin"),
|
||||||
|
observed_at=observed,
|
||||||
|
published_at=article.get("published_at"),
|
||||||
|
source_url=article["url"],
|
||||||
|
confidence=confidence,
|
||||||
|
extracted_by=model,
|
||||||
|
raw_excerpt=(article.get("summary") or article["title"])[:400],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return out, model
|
||||||
|
|
||||||
|
|
||||||
|
MAX_ARTICLES_PER_RUN = int(os.environ.get("FUEL_PROMO_MAX_PER_RUN", "3"))
|
||||||
|
|
||||||
|
|
||||||
|
def collect(models=None, force=False, limit=None):
|
||||||
|
"""Recherche les opérations, n'analyse que les nouveaux articles, enregistre les annonces.
|
||||||
|
|
||||||
|
Chaque extraction prend environ 2 à 3 minutes avec mistral-small3.2:24b : le nombre
|
||||||
|
d'articles par passage reste volontairement bas pour que le passage reste borné.
|
||||||
|
"""
|
||||||
|
articles, errors = gather()
|
||||||
|
fresh = storage.save_articles(articles, "promotions")
|
||||||
|
todo = [article for article in fresh if article.get("topic")][: limit or MAX_ARTICLES_PER_RUN]
|
||||||
|
saved, analysed = 0, []
|
||||||
|
for article in todo:
|
||||||
|
try:
|
||||||
|
found, _model = analyse(article, models=models)
|
||||||
|
except Exception as exc:
|
||||||
|
errors.append(f"ollama {article['hash'][:6]}: {type(exc).__name__}")
|
||||||
|
continue
|
||||||
|
if found:
|
||||||
|
saved += storage.save_promotions(found)
|
||||||
|
analysed.append(article["hash"])
|
||||||
|
storage.mark_analysed(analysed)
|
||||||
|
newest = max([article.get("published_at") or "" for article in articles] or [""])
|
||||||
|
return dict(
|
||||||
|
status="ok" if articles else "error",
|
||||||
|
articles=len(articles),
|
||||||
|
new=len(todo),
|
||||||
|
analysed=len(analysed),
|
||||||
|
promotions=saved,
|
||||||
|
errors=errors[:6],
|
||||||
|
last_observation_at=newest or None,
|
||||||
|
detail="; ".join(errors[:3]) if errors else f"{saved} opération(s) enregistrée(s)",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def active(today=None):
|
||||||
|
"""Opérations en cours ou à venir, avec leur source — pour l'affichage et le conseil."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
today = today or datetime.now(timezone.utc).date()
|
||||||
|
out = []
|
||||||
|
for row in storage.promotions(today=today):
|
||||||
|
if row.get("valid_from") and row["valid_from"] > today.isoformat():
|
||||||
|
state = "annoncée"
|
||||||
|
else:
|
||||||
|
state = "en cours"
|
||||||
|
out.append(dict(row, state=state))
|
||||||
|
return out
|
||||||
8
schedule.sh
Executable file
8
schedule.sh
Executable file
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Point d'entrée unique de l'ordonnanceur : chaque collecteur décide s'il est dû.
|
||||||
|
if [ -f /etc/fuel-advisor.env ]; then
|
||||||
|
set -a
|
||||||
|
. /etc/fuel-advisor.env
|
||||||
|
set +a
|
||||||
|
fi
|
||||||
|
exec /usr/bin/python3 /opt/fuel-advisor/scheduler.py --run "$@"
|
||||||
262
scheduler.py
Normal file
262
scheduler.py
Normal file
@@ -0,0 +1,262 @@
|
|||||||
|
"""Ordonnanceur multi-fréquences : chaque source a sa propre temporalité.
|
||||||
|
|
||||||
|
Un seul point d'entrée (`scheduler.py --run`) prévu toutes les 10 minutes : il ne déclenche
|
||||||
|
que les collecteurs réellement dus, enregistre pour chacun source, fréquence, dernière
|
||||||
|
exécution réussie, dernière observation disponible, prochaine exécution et état.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import fcntl
|
||||||
|
import json
|
||||||
|
from datetime import datetime, time, timedelta, timezone
|
||||||
|
|
||||||
|
import storage
|
||||||
|
|
||||||
|
PARIS = storage.PARIS
|
||||||
|
|
||||||
|
|
||||||
|
def _now_paris(now=None):
|
||||||
|
return (now or datetime.now(timezone.utc)).astimezone(PARIS)
|
||||||
|
|
||||||
|
|
||||||
|
def _job_local(now=None):
|
||||||
|
"""Emplacement des implémentations (colonne vertébrale pilotée par ce module)."""
|
||||||
|
import collector
|
||||||
|
|
||||||
|
return collector
|
||||||
|
|
||||||
|
|
||||||
|
def _window(*, weekdays=None, after=None, before=None):
|
||||||
|
"""Fenêtre horaire optionnelle : jours de la semaine et plage horaire (heure de Paris)."""
|
||||||
|
|
||||||
|
def check(now=None):
|
||||||
|
moment = _now_paris(now)
|
||||||
|
if weekdays is not None and moment.weekday() not in weekdays:
|
||||||
|
return False
|
||||||
|
if after is not None and moment.time() < after:
|
||||||
|
return False
|
||||||
|
if before is not None and moment.time() > before:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
return check
|
||||||
|
|
||||||
|
|
||||||
|
def _daily_at(hour, minute=0, weekdays=None):
|
||||||
|
after = time(hour, minute)
|
||||||
|
return _window(weekdays=weekdays, after=after)
|
||||||
|
|
||||||
|
|
||||||
|
JOBS = {
|
||||||
|
"local_prices": dict(
|
||||||
|
source="prix-carburants.gouv.fr (flux instantané public)",
|
||||||
|
frequency="chaque heure, 24/7, pour chaque zone favorite",
|
||||||
|
cadence_seconds=3600,
|
||||||
|
retry_seconds=600,
|
||||||
|
window=lambda now=None: True,
|
||||||
|
func="job_local_prices",
|
||||||
|
note="n’historise un événement que si le prix ou l’horodatage déclaré change",
|
||||||
|
),
|
||||||
|
"market_daily": dict(
|
||||||
|
source="Brent quotidien (Stooq, puis page publique ; clé EIA si fournie)",
|
||||||
|
frequency="1 fois par jour, avec nouvelle tentative en cas d’échec",
|
||||||
|
cadence_seconds=86400,
|
||||||
|
retry_seconds=1800,
|
||||||
|
window=_daily_at(6, 30),
|
||||||
|
func="job_market_daily",
|
||||||
|
note="la date retenue est celle de l’observation publiée, pas celle du téléchargement",
|
||||||
|
),
|
||||||
|
"ecb_fx": dict(
|
||||||
|
source="BCE – taux USD/EUR (EXR, API officielle)",
|
||||||
|
frequency="jours ouvrés, après la publication vers 16 h",
|
||||||
|
cadence_seconds=86400,
|
||||||
|
retry_seconds=1800,
|
||||||
|
window=_window(weekdays=(0, 1, 2, 3, 4), after=time(16, 15)),
|
||||||
|
func="job_ecb_fx",
|
||||||
|
note="aucune publication le samedi et le dimanche",
|
||||||
|
),
|
||||||
|
"eu_bulletin": dict(
|
||||||
|
source="Commission européenne – Weekly Oil Bulletin (France TTC et hors taxes)",
|
||||||
|
frequency="le jeudi (publication hebdomadaire)",
|
||||||
|
cadence_seconds=7 * 86400,
|
||||||
|
retry_seconds=3600,
|
||||||
|
window=_daily_at(13, 0, weekdays=(3,)),
|
||||||
|
func="job_eu_bulletin",
|
||||||
|
note="les prix sont ceux de la semaine publiée",
|
||||||
|
),
|
||||||
|
"dgec_monthly": dict(
|
||||||
|
source="DGEC – Brent, marge brute de raffinage, prix HTT/TTC France",
|
||||||
|
frequency="mensuel, avec détection d’une nouvelle période",
|
||||||
|
cadence_seconds=86400,
|
||||||
|
retry_seconds=3600,
|
||||||
|
window=_daily_at(7, 0),
|
||||||
|
func="job_dgec_monthly",
|
||||||
|
note="un contrôle quotidien évite de rater la publication du mois",
|
||||||
|
),
|
||||||
|
"portwatch": dict(
|
||||||
|
source="IMF PortWatch – passages par détroit (base du moniteur IEA)",
|
||||||
|
frequency="1 fois par jour, fenêtre glissante pour les révisions",
|
||||||
|
cadence_seconds=86400,
|
||||||
|
retry_seconds=3600,
|
||||||
|
window=_daily_at(8, 0),
|
||||||
|
func="job_portwatch",
|
||||||
|
note="publication différée de plusieurs jours : la date affichée est celle de l’observation",
|
||||||
|
),
|
||||||
|
"news_geo": dict(
|
||||||
|
source="Actualités géopolitiques et logistiques (Google News RSS, GDELT)",
|
||||||
|
frequency="toutes les 2 heures",
|
||||||
|
cadence_seconds=2 * 3600,
|
||||||
|
retry_seconds=1800,
|
||||||
|
window=lambda now=None: True,
|
||||||
|
func="job_news_geo",
|
||||||
|
note="Ollama n’est relancé que pour un article jamais analysé",
|
||||||
|
),
|
||||||
|
"promotions": dict(
|
||||||
|
source="Opérations commerciales des enseignes (actualités, sources publiques)",
|
||||||
|
frequency="plusieurs fois par jour (matin, midi, soir)",
|
||||||
|
cadence_seconds=8 * 3600,
|
||||||
|
retry_seconds=1800,
|
||||||
|
window=_window(after=time(7, 30), before=time(21, 30)),
|
||||||
|
func="job_promotions",
|
||||||
|
note="annonces futures conservées avec début et fin de validité",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def is_due(name, now=None, force=False):
|
||||||
|
"""Un collecteur est dû selon sa cadence, sa fenêtre et l’état de sa dernière exécution."""
|
||||||
|
job = JOBS[name]
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
if force:
|
||||||
|
return True
|
||||||
|
if not job["window"](now):
|
||||||
|
return False
|
||||||
|
state = storage.job_get(name)
|
||||||
|
if not state or not state.get("last_run_at"):
|
||||||
|
return True
|
||||||
|
last = datetime.fromisoformat(state["last_run_at"])
|
||||||
|
delay = job["cadence_seconds"]
|
||||||
|
if state.get("status") == "error":
|
||||||
|
delay = min(delay, job.get("retry_seconds", 900))
|
||||||
|
return now - last >= timedelta(seconds=delay)
|
||||||
|
|
||||||
|
|
||||||
|
def next_run(name, now=None):
|
||||||
|
"""Prochaine exécution estimée, en tenant compte de la fenêtre autorisée."""
|
||||||
|
job = JOBS[name]
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
if not job["window"](now):
|
||||||
|
probe = now
|
||||||
|
for _ in range(0, 8 * 24 * 4):
|
||||||
|
probe = probe + timedelta(minutes=15)
|
||||||
|
if job["window"](probe):
|
||||||
|
break
|
||||||
|
now = probe
|
||||||
|
state = storage.job_get(name)
|
||||||
|
if not state or not state.get("last_run_at"):
|
||||||
|
return now.isoformat()
|
||||||
|
last = datetime.fromisoformat(state["last_run_at"])
|
||||||
|
delay = job["cadence_seconds"]
|
||||||
|
if state.get("status") == "error":
|
||||||
|
delay = min(delay, job.get("retry_seconds", 900))
|
||||||
|
candidate = max(now, last + timedelta(seconds=delay))
|
||||||
|
probe = candidate
|
||||||
|
for _ in range(0, 8 * 24 * 4):
|
||||||
|
if job["window"](probe):
|
||||||
|
break
|
||||||
|
probe = probe + timedelta(minutes=15)
|
||||||
|
return probe.isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def run(names=None, force=False, now=None):
|
||||||
|
"""Exécute les collecteurs dus. Ne renvoie jamais d’exception : chaque échec est supervisé."""
|
||||||
|
collector = _job_local(now)
|
||||||
|
results = {}
|
||||||
|
storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with (storage.DB_PATH.parent / "scheduler.lock").open("a") as lock:
|
||||||
|
try:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except BlockingIOError:
|
||||||
|
return {"status": "busy", "results": {}}
|
||||||
|
for name, job in JOBS.items():
|
||||||
|
if names and name not in names:
|
||||||
|
continue
|
||||||
|
if not is_due(name, now=now, force=force):
|
||||||
|
results[name] = {"status": "not_due", "next_run_at": next_run(name, now)}
|
||||||
|
continue
|
||||||
|
started = datetime.now(timezone.utc)
|
||||||
|
try:
|
||||||
|
outcome = getattr(collector, job["func"])(force=force)
|
||||||
|
except Exception as exc:
|
||||||
|
outcome = {"status": "error", "detail": f"{type(exc).__name__}: {str(exc)[:200]}"}
|
||||||
|
state = storage.job_record(
|
||||||
|
name,
|
||||||
|
job["source"],
|
||||||
|
job["frequency"],
|
||||||
|
job["cadence_seconds"],
|
||||||
|
outcome.get("status", "error"),
|
||||||
|
detail=outcome.get("detail", ""),
|
||||||
|
stored=int(outcome.get("stored") or outcome.get("promotions") or 0),
|
||||||
|
last_observation_at=outcome.get("last_observation_at"),
|
||||||
|
next_run_at=next_run(name),
|
||||||
|
now=started,
|
||||||
|
)
|
||||||
|
results[name] = dict(
|
||||||
|
outcome,
|
||||||
|
next_run_at=state["next_run_at"],
|
||||||
|
duration_s=round((datetime.now(timezone.utc) - started).total_seconds(), 1),
|
||||||
|
)
|
||||||
|
return {"status": "ok", "results": results}
|
||||||
|
|
||||||
|
|
||||||
|
def inventory(now=None):
|
||||||
|
"""Inventaire lisible des collecteurs, pour la supervision et la page diagnostic."""
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
rows = []
|
||||||
|
for name, job in JOBS.items():
|
||||||
|
state = storage.job_get(name) or {}
|
||||||
|
rows.append(
|
||||||
|
dict(
|
||||||
|
name=name,
|
||||||
|
source=job["source"],
|
||||||
|
frequency=job["frequency"],
|
||||||
|
note=job.get("note", ""),
|
||||||
|
cadence_seconds=job["cadence_seconds"],
|
||||||
|
last_run_at=state.get("last_run_at"),
|
||||||
|
last_success_at=state.get("last_success_at"),
|
||||||
|
last_observation_at=state.get("last_observation_at"),
|
||||||
|
next_run_at=next_run(name, now),
|
||||||
|
status=state.get("status", "never"),
|
||||||
|
detail=state.get("detail", ""),
|
||||||
|
stored=state.get("stored", 0),
|
||||||
|
run_count=state.get("run_count", 0),
|
||||||
|
fail_count=state.get("fail_count", 0),
|
||||||
|
due=is_due(name, now=now),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="Ordonnanceur des collecteurs carburant")
|
||||||
|
parser.add_argument("--run", action="store_true", help="exécuter les collecteurs dus")
|
||||||
|
parser.add_argument("--force", action="store_true", help="ignorer cadence et fenêtres")
|
||||||
|
parser.add_argument("--only", action="append", help="limiter à un ou plusieurs collecteurs")
|
||||||
|
parser.add_argument("--list", action="store_true", help="afficher l’inventaire")
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.list:
|
||||||
|
for row in inventory():
|
||||||
|
print(json.dumps(row, ensure_ascii=False))
|
||||||
|
return 0
|
||||||
|
if args.run:
|
||||||
|
outcome = run(names=args.only, force=args.force)
|
||||||
|
print(json.dumps(outcome, ensure_ascii=False, default=str))
|
||||||
|
return 0 if outcome.get("status") == "ok" else 1
|
||||||
|
parser.print_help()
|
||||||
|
return 2
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
317
storage.py
317
storage.py
@@ -45,12 +45,15 @@ def record_observations(rows, now=None):
|
|||||||
key = (row["id"], fuel, day)
|
key = (row["id"], fuel, day)
|
||||||
values[key] = (*key, price, row["updates"].get(fuel, ""), now.isoformat(), row["lat"], row["lon"])
|
values[key] = (*key, price, row["updates"].get(fuel, ""), now.isoformat(), row["lat"], row["lon"])
|
||||||
with connect() as db:
|
with connect() as db:
|
||||||
|
rows_with_meta = [(*value, value[3], value[4]) for value in values.values()]
|
||||||
db.executemany(
|
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,
|
ON CONFLICT(station_id,fuel,day) DO UPDATE SET price=excluded.price,
|
||||||
source_updated=excluded.source_updated,collected_at=excluded.collected_at,
|
source_updated=excluded.source_updated,collected_at=excluded.collected_at,
|
||||||
lat=excluded.lat,lon=excluded.lon""",
|
lat=excluded.lat,lon=excluded.lon,published_at=excluded.published_at,
|
||||||
list(values.values()),
|
fetched_at=excluded.fetched_at""",
|
||||||
|
rows_with_meta,
|
||||||
)
|
)
|
||||||
# Noms/communes/type de voie conservés une fois par station (affichage des graphiques).
|
# Noms/communes/type de voie conservés une fois par station (affichage des graphiques).
|
||||||
seen = {
|
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)."""
|
"""Historise une série amont officielle (idempotent : la même date remplace la valeur)."""
|
||||||
now = now or datetime.now(timezone.utc)
|
now = now or datetime.now(timezone.utc)
|
||||||
values = [
|
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
|
for row in rows
|
||||||
if row.get("day") and isinstance(row.get("value"), (int, float)) and math.isfinite(row["value"])
|
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
|
return 0
|
||||||
with connect() as db:
|
with connect() as db:
|
||||||
db.executemany(
|
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,
|
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,
|
values,
|
||||||
)
|
)
|
||||||
return len(values)
|
return len(values)
|
||||||
@@ -140,6 +154,7 @@ def save_upstream(series, rows, unit, source, now=None):
|
|||||||
def save_chokepoints(entries, source, now=None):
|
def save_chokepoints(entries, source, now=None):
|
||||||
"""Historise les passages observés par détroit (source IMF PortWatch)."""
|
"""Historise les passages observés par détroit (source IMF PortWatch)."""
|
||||||
now = now or datetime.now(timezone.utc)
|
now = now or datetime.now(timezone.utc)
|
||||||
|
pairs = entries.items() if isinstance(entries, dict) else (entries or [])
|
||||||
values = [
|
values = [
|
||||||
(
|
(
|
||||||
name,
|
name,
|
||||||
@@ -151,8 +166,8 @@ def save_chokepoints(entries, source, now=None):
|
|||||||
str(source),
|
str(source),
|
||||||
now.isoformat(),
|
now.isoformat(),
|
||||||
)
|
)
|
||||||
for name, entry in (entries or {}).items()
|
for name, entry in pairs
|
||||||
if entry.get("day")
|
if entry and entry.get("day")
|
||||||
]
|
]
|
||||||
if not values:
|
if not values:
|
||||||
return 0
|
return 0
|
||||||
@@ -230,6 +245,261 @@ def chokepoint_daily(days=60):
|
|||||||
return out
|
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):
|
def set_brands(pairs, now=None):
|
||||||
"""Mémorise les enseignes trouvées (station_id -> enseigne) sans écraser par du vide."""
|
"""Mémorise les enseignes trouvées (station_id -> enseigne) sans écraser par du vide."""
|
||||||
now = now or datetime.now(timezone.utc)
|
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,
|
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 '',
|
chokepoints INTEGER NOT NULL DEFAULT 0, detail TEXT NOT NULL DEFAULT '',
|
||||||
finished_at TEXT NOT NULL);
|
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_day ON observations(day);
|
||||||
CREATE INDEX IF NOT EXISTS observations_station ON observations(station_id);
|
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
|
yield db
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
|
|||||||
@@ -1,23 +1,32 @@
|
|||||||
"""Fixtures partagées : aucune base de production, aucun accès réseau."""
|
"""Fixtures partagées : aucune base de production, aucun accès réseau, aucun appel de modèle."""
|
||||||
|
|
||||||
import importlib
|
import importlib
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import brands
|
import brands
|
||||||
|
import llm
|
||||||
import market
|
import market
|
||||||
|
import news
|
||||||
|
import promotions
|
||||||
import storage
|
import storage
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def isolated_database(tmp_path, monkeypatch):
|
def isolated_environment(tmp_path, monkeypatch):
|
||||||
"""Toutes les bases pointent vers un fichier temporaire, jamais /var/lib."""
|
"""Bases temporaires, aucune source réseau, aucun appel Ollama."""
|
||||||
for module in (storage, brands, market):
|
for module in (storage, brands, market):
|
||||||
monkeypatch.setattr(module, "DB_PATH", tmp_path / f"{module.__name__}.sqlite3")
|
monkeypatch.setattr(module, "DB_PATH", tmp_path / f"{module.__name__}.sqlite3")
|
||||||
# Aucun test ne doit interroger Nominatim ou un fournisseur de cours.
|
|
||||||
monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: [])
|
monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: [])
|
||||||
monkeypatch.setattr(market, "PROVIDERS", {})
|
monkeypatch.setattr(market, "PROVIDERS", {})
|
||||||
# Aucun test ne doit sortir sur le réseau pour les sources amont.
|
monkeypatch.setattr(news, "gather", lambda *args, **kwargs: ([], []))
|
||||||
|
monkeypatch.setattr(promotions, "gather", lambda *args, **kwargs: ([], []))
|
||||||
|
monkeypatch.setattr(
|
||||||
|
llm,
|
||||||
|
"extract",
|
||||||
|
lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("Ollama non appelé pendant les tests")),
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(llm, "available", lambda *args, **kwargs: [])
|
||||||
collector = importlib.import_module("collector")
|
collector = importlib.import_module("collector")
|
||||||
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
|
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
|
||||||
return tmp_path
|
return tmp_path
|
||||||
|
|||||||
194
tests/test_collectors.py
Normal file
194
tests/test_collectors.py
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
"""Événements prix (changement uniquement), actualités structurées et opérations commerciales."""
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import collector
|
||||||
|
import llm
|
||||||
|
import news
|
||||||
|
import promotions
|
||||||
|
import storage
|
||||||
|
|
||||||
|
|
||||||
|
def flux_row(price=1.9, declared="2026-09-12 08:00:00", station="S1", fuel="Gazole"):
|
||||||
|
return {
|
||||||
|
"id": station,
|
||||||
|
"name": "RUE TEST",
|
||||||
|
"city": "Nantes",
|
||||||
|
"lat": 48.8,
|
||||||
|
"lon": 2.3,
|
||||||
|
"prices": {fuel: price},
|
||||||
|
"updates": {fuel: declared},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_price_events_only_on_change(store):
|
||||||
|
now = datetime(2026, 9, 12, 10, 0, tzinfo=timezone.utc)
|
||||||
|
assert storage.record_price_events([flux_row()], now) == 1, "première observation"
|
||||||
|
assert storage.record_price_events([flux_row()], now + timedelta(hours=1)) == 0, "identique"
|
||||||
|
assert storage.record_price_events([flux_row(price=1.87)], now + timedelta(hours=2)) == 1
|
||||||
|
assert storage.record_price_events([flux_row(price=1.87)], now + timedelta(hours=3)) == 0
|
||||||
|
assert (
|
||||||
|
storage.record_price_events(
|
||||||
|
[flux_row(price=1.87, declared="2026-09-12 12:00:00")], now + timedelta(hours=4)
|
||||||
|
)
|
||||||
|
== 1
|
||||||
|
), "nouvel horodatage déclaré par la station"
|
||||||
|
events = storage.price_events(days=30)
|
||||||
|
assert len(events) == 3, "pas de doublon pour un prix identique"
|
||||||
|
baisse = [event for event in events if event["price"] == 1.87 and event["previous_price"] == 1.9]
|
||||||
|
assert len(baisse) == 1, "baisse de 3 c€ enregistrée"
|
||||||
|
redeclared = [event for event in events if event["declared_at"] == "2026-09-12 12:00:00"][0]
|
||||||
|
assert redeclared["price"] == 1.87 and redeclared["previous_price"] == 1.87, (
|
||||||
|
"même prix mais nouvel horodatage déclaré"
|
||||||
|
)
|
||||||
|
assert redeclared["fetched_at"] and redeclared["fetched_at"] != redeclared["declared_at"], (
|
||||||
|
"la date de téléchargement ne remplace pas la date d’observation"
|
||||||
|
)
|
||||||
|
assert redeclared["source"].startswith("prix-carburants.gouv.fr")
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_prices_job_needs_favorites_and_records_events(store):
|
||||||
|
assert collector.job_local_prices(load=lambda: [flux_row()])["status"] == "unchanged"
|
||||||
|
store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=5))
|
||||||
|
out = collector.job_local_prices(load=lambda: [flux_row()])
|
||||||
|
assert out["status"] == "ok" and out["events"] == 1
|
||||||
|
assert out["last_observation_at"] == "2026-09-12 08:00:00"
|
||||||
|
assert collector.job_local_prices(load=lambda: [flux_row()])["events"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_rss_articles_keep_publication_date_and_source():
|
||||||
|
xml = b"""<?xml version="1.0"?><rss version="2.0"><channel>
|
||||||
|
<item><title>Attaque en mer Rouge sur un pétrolier</title>
|
||||||
|
<link>https://exemple.fr/a1</link><pubDate>Fri, 11 Sep 2026 09:30:00 GMT</pubDate>
|
||||||
|
<source>Agence Test</source><description><p>Un pétrolier visé.</p></description></item>
|
||||||
|
</channel></rss>"""
|
||||||
|
articles = news.parse_rss(xml, "Google News", "suez_babelmandeb")
|
||||||
|
assert len(articles) == 1
|
||||||
|
article = articles[0]
|
||||||
|
assert article["published_at"] == "2026-09-11", "date de publication conservée"
|
||||||
|
assert article["observed_at"] == "2026-09-11"
|
||||||
|
assert article["source"] == "Agence Test"
|
||||||
|
assert "<" not in article["title"] and "pétrolier" in article["title"]
|
||||||
|
assert len(article["hash"]) == 32
|
||||||
|
|
||||||
|
|
||||||
|
def test_news_only_calls_llm_for_new_articles(store, monkeypatch):
|
||||||
|
article = dict(
|
||||||
|
hash="h1",
|
||||||
|
url="https://exemple.fr/a1",
|
||||||
|
title="Ormuz bloqué",
|
||||||
|
topic="ormuz",
|
||||||
|
source="Test",
|
||||||
|
published_at="2026-09-11",
|
||||||
|
observed_at="2026-09-11",
|
||||||
|
summary="Détroit fermé.",
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(news, "gather", lambda *a, **k: ([article], []))
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_extract(prompt, models=None):
|
||||||
|
calls.append(prompt)
|
||||||
|
return {
|
||||||
|
"pertinent": True,
|
||||||
|
"evenements": [
|
||||||
|
{
|
||||||
|
"type": "chokepoint",
|
||||||
|
"direction": "hausse",
|
||||||
|
"magnitude": "forte",
|
||||||
|
"carburants": ["gazole"],
|
||||||
|
"zone": "Ormuz",
|
||||||
|
"horizon_jours": 12,
|
||||||
|
"confiance": 0.7,
|
||||||
|
"debut": "2026-09-11",
|
||||||
|
"fin": None,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}, "mistral-small3.2:24b"
|
||||||
|
|
||||||
|
monkeypatch.setattr(llm, "extract", fake_extract)
|
||||||
|
first = news.collect()
|
||||||
|
assert first["analysed"] == 1 and first["events"] == 1
|
||||||
|
assert len(calls) == 1
|
||||||
|
second = news.collect()
|
||||||
|
assert second["analysed"] == 0, "aucun nouvel article, aucun appel au modèle"
|
||||||
|
assert len(calls) == 1
|
||||||
|
events = storage.news_events()
|
||||||
|
assert events[0]["direction"] == "hausse"
|
||||||
|
assert events[0]["valid_from"] == "2026-09-11" and events[0]["valid_until"] == "2026-09-23"
|
||||||
|
assert events[0]["source_url"] == "https://exemple.fr/a1", "aucun signal sans source"
|
||||||
|
assert events[0]["extracted_by"] == "mistral-small3.2:24b"
|
||||||
|
|
||||||
|
|
||||||
|
def test_news_rejects_unrelated_article(store, monkeypatch):
|
||||||
|
article = dict(
|
||||||
|
hash="h2",
|
||||||
|
url="https://exemple.fr/a2",
|
||||||
|
title="Recette de cuisine",
|
||||||
|
topic="ormuz",
|
||||||
|
source="Test",
|
||||||
|
published_at="2026-09-11",
|
||||||
|
observed_at="2026-09-11",
|
||||||
|
summary="Gâteau.",
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(news, "gather", lambda *a, **k: ([article], []))
|
||||||
|
monkeypatch.setattr(llm, "extract", lambda prompt, models=None: ({"pertinent": False}, "m"))
|
||||||
|
out = news.collect()
|
||||||
|
assert out["events"] == 0 and storage.news_events() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_promotions_extraction_keeps_only_sourced_and_known_brands(store, monkeypatch):
|
||||||
|
article = dict(
|
||||||
|
hash="p1",
|
||||||
|
url="https://exemple.fr/promo",
|
||||||
|
title="Carburant à prix coûtant chez E.Leclerc",
|
||||||
|
topic="_general",
|
||||||
|
source="Test",
|
||||||
|
published_at="2026-09-12",
|
||||||
|
observed_at="2026-09-12",
|
||||||
|
summary="Ce week-end, E.Leclerc vend le gazole à prix coûtant.",
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(promotions, "gather", lambda use_gdelt=True: ([article], []))
|
||||||
|
monkeypatch.setattr(
|
||||||
|
llm,
|
||||||
|
"extract",
|
||||||
|
lambda prompt, models=None: (
|
||||||
|
{
|
||||||
|
"operations": [
|
||||||
|
{
|
||||||
|
"enseigne": "E.Leclerc",
|
||||||
|
"nature": "prix_coutant",
|
||||||
|
"remise_par_litre": None,
|
||||||
|
"carburants": ["gazole"],
|
||||||
|
"zone": "France",
|
||||||
|
"debut": "2026-09-13",
|
||||||
|
"fin": "2026-09-14",
|
||||||
|
"confiance": 0.9,
|
||||||
|
},
|
||||||
|
{"enseigne": "Enseigne Inventée", "nature": "remise_litre", "debut": "2026-09-13"},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"mistral-small3.2:24b",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
out = promotions.collect()
|
||||||
|
assert out["promotions"] == 1, "enseigne absente du texte rejetée"
|
||||||
|
rows = storage.promotions(today=datetime(2026, 9, 13, tzinfo=timezone.utc).date())
|
||||||
|
assert rows[0]["brand"] == "E.Leclerc"
|
||||||
|
assert rows[0]["valid_from"] == "2026-09-13" and rows[0]["valid_until"] == "2026-09-14"
|
||||||
|
assert rows[0]["confidence"] == pytest.approx(0.9)
|
||||||
|
assert rows[0]["source_url"] == "https://exemple.fr/promo"
|
||||||
|
assert rows[0]["observed_at"] == "2026-09-12"
|
||||||
|
active = promotions.active(today=datetime(2026, 9, 13, tzinfo=timezone.utc).date())
|
||||||
|
assert active[0]["state"] == "en cours"
|
||||||
|
announced = promotions.active(today=datetime(2026, 9, 12, tzinfo=timezone.utc).date())
|
||||||
|
assert announced[0]["state"] == "annoncée"
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_json_parsing_tolerates_wrapping():
|
||||||
|
data, _ = llm.parse_json('```json\n{"pertinent": true, "evenements": []}\n```'), None
|
||||||
|
assert data["pertinent"] is True
|
||||||
|
assert llm.parse_json('Voici : {"a": 1} voilà') == {"a": 1}
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
llm.parse_json("aucun json ici")
|
||||||
@@ -122,12 +122,63 @@ def test_http_history_exposes_average_and_stations(server, store):
|
|||||||
assert out["stations_series"][0]["station_id"] == "A"
|
assert out["stations_series"][0]["station_id"] == "A"
|
||||||
|
|
||||||
|
|
||||||
|
def test_http_jobs_inventory_exposes_sources_and_schedules(server):
|
||||||
|
code, out = request(server, "GET", "/api/jobs")
|
||||||
|
assert code == 200
|
||||||
|
jobs = {job["name"]: job for job in out["jobs"]}
|
||||||
|
assert jobs["local_prices"]["source"].startswith("prix-carburants.gouv.fr")
|
||||||
|
assert jobs["local_prices"]["frequency"] == "chaque heure, 24/7, pour chaque zone favorite"
|
||||||
|
assert jobs["eu_bulletin"]["frequency"] == "le jeudi (publication hebdomadaire)"
|
||||||
|
assert jobs["news_geo"]["frequency"] == "toutes les 2 heures"
|
||||||
|
assert jobs["ecb_fx"]["frequency"].startswith("jours ouvrés")
|
||||||
|
for job in jobs.values():
|
||||||
|
assert job["next_run_at"] and job["status"] in ("never", "ok", "unchanged", "error")
|
||||||
|
|
||||||
|
|
||||||
|
def test_http_advice_reports_refresh_and_promotions(server, store, monkeypatch):
|
||||||
|
monkeypatch.setattr(
|
||||||
|
app.collector,
|
||||||
|
"ensure_fresh_local",
|
||||||
|
lambda max_age_seconds=900: dict(refreshed=True, age_seconds=1200.0),
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
app.promotions,
|
||||||
|
"active",
|
||||||
|
lambda: [
|
||||||
|
dict(
|
||||||
|
brand="E.Leclerc",
|
||||||
|
nature="prix_coutant",
|
||||||
|
fuels="Gazole",
|
||||||
|
state="en cours",
|
||||||
|
valid_from="2026-09-12",
|
||||||
|
valid_until="2026-09-13",
|
||||||
|
stations="",
|
||||||
|
source_url="https://exemple.fr/promo",
|
||||||
|
confidence=0.9,
|
||||||
|
discount_per_liter=None,
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
row = sample(datetime.now(timezone.utc))
|
||||||
|
row.update(name="A", city="Paris", address="Rue")
|
||||||
|
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [row])
|
||||||
|
code, out = request(
|
||||||
|
server, "POST", "/api/advice", {"lat": 48.8, "lon": 2.3, "radius_km": 15, "fuel": "Gazole"}
|
||||||
|
)
|
||||||
|
assert code == 200
|
||||||
|
assert out["local_refresh"]["refreshed"] is True
|
||||||
|
assert out["promotions"][0]["brand"] == "E.Leclerc"
|
||||||
|
assert "pas forcément la moins chère" in out["promotions_note"]
|
||||||
|
|
||||||
|
|
||||||
def test_http_ui_and_validation(server):
|
def test_http_ui_and_validation(server):
|
||||||
status, html = request(server, "GET", "/")
|
status, html = request(server, "GET", "/")
|
||||||
assert status == 200
|
assert status == 200
|
||||||
assert "Autonomie restante" in html
|
assert "Autonomie restante" in html
|
||||||
assert "Mes favoris" in html
|
assert "Mes favoris" in html
|
||||||
|
assert "Supervision" in html
|
||||||
code, js = request(server, "GET", "/ui.js")
|
code, js = request(server, "GET", "/ui.js")
|
||||||
|
assert "loadJobs" in js and "promotionsBlock" in js
|
||||||
assert code == 200
|
assert code == 200
|
||||||
assert "stationCards" in js and "averageChart" in js
|
assert "stationCards" in js and "averageChart" in js
|
||||||
assert (
|
assert (
|
||||||
|
|||||||
98
tests/test_scheduler.py
Normal file
98
tests/test_scheduler.py
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
"""Ordonnanceur : cadences propres à chaque source, fenêtres, supervision, résilience."""
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import collector
|
||||||
|
import scheduler
|
||||||
|
import storage
|
||||||
|
|
||||||
|
|
||||||
|
def test_registry_covers_every_source_with_its_own_cadence():
|
||||||
|
expected = {
|
||||||
|
"local_prices",
|
||||||
|
"market_daily",
|
||||||
|
"ecb_fx",
|
||||||
|
"eu_bulletin",
|
||||||
|
"dgec_monthly",
|
||||||
|
"portwatch",
|
||||||
|
"news_geo",
|
||||||
|
"promotions",
|
||||||
|
}
|
||||||
|
assert expected <= set(scheduler.JOBS)
|
||||||
|
for name, job in scheduler.JOBS.items():
|
||||||
|
assert job["source"] and job["frequency"], name
|
||||||
|
assert job["cadence_seconds"] > 0, name
|
||||||
|
assert callable(job["window"]), name
|
||||||
|
assert hasattr(collector, job["func"]), name
|
||||||
|
assert scheduler.JOBS["local_prices"]["cadence_seconds"] == 3600, "prix locaux : toutes les heures"
|
||||||
|
assert scheduler.JOBS["news_geo"]["cadence_seconds"] == 7200, "actualités : toutes les 2 heures"
|
||||||
|
|
||||||
|
|
||||||
|
def test_job_is_due_only_within_its_window(store, monkeypatch):
|
||||||
|
monkeypatch.setattr(scheduler, "JOBS", dict(scheduler.JOBS, ecb_fx=dict(scheduler.JOBS["ecb_fx"])))
|
||||||
|
saturday = datetime(2026, 9, 12, 17, 0, tzinfo=timezone.utc) # samedi 19 h à Paris
|
||||||
|
monday_morning = datetime(2026, 9, 14, 8, 0, tzinfo=timezone.utc) # lundi 10 h
|
||||||
|
monday_evening = datetime(2026, 9, 14, 14, 30, tzinfo=timezone.utc) # lundi 16 h 30
|
||||||
|
assert scheduler.is_due("ecb_fx", now=monday_evening) is True
|
||||||
|
assert scheduler.is_due("ecb_fx", now=saturday) is False
|
||||||
|
assert scheduler.is_due("ecb_fx", now=monday_morning) is False
|
||||||
|
assert scheduler.is_due("local_prices", now=saturday) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_cadence_and_retry_after_failure(store):
|
||||||
|
now = datetime(2026, 9, 14, 12, 0, tzinfo=timezone.utc)
|
||||||
|
storage.job_record("news_geo", "src", "freq", 7200, "ok", now=now)
|
||||||
|
assert scheduler.is_due("news_geo", now=now + timedelta(minutes=30)) is False
|
||||||
|
assert scheduler.is_due("news_geo", now=now + timedelta(hours=2)) is True
|
||||||
|
storage.job_record("news_geo", "src", "freq", 7200, "error", now=now)
|
||||||
|
assert scheduler.is_due("news_geo", now=now + timedelta(minutes=31)) is True, "réessai après échec"
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_run_respects_window(store):
|
||||||
|
sunday = datetime(2026, 9, 13, 10, 0, tzinfo=timezone.utc) # dimanche
|
||||||
|
upcoming = scheduler.next_run("eu_bulletin", now=sunday)
|
||||||
|
assert datetime.fromisoformat(upcoming).astimezone(storage.PARIS).weekday() == 3, "jeudi"
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_records_supervision_and_survives_failures(store, monkeypatch):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def good(force=False):
|
||||||
|
calls.append("local_prices")
|
||||||
|
return dict(status="ok", stored=3, last_observation_at="2026-09-12T18:00:00", detail="3 changements")
|
||||||
|
|
||||||
|
def broken(force=False):
|
||||||
|
calls.append("portwatch")
|
||||||
|
raise OSError("source hors ligne")
|
||||||
|
|
||||||
|
monkeypatch.setattr(collector, "job_local_prices", good)
|
||||||
|
monkeypatch.setattr(collector, "job_portwatch", broken)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
scheduler,
|
||||||
|
"JOBS",
|
||||||
|
{
|
||||||
|
name: dict(scheduler.JOBS[name], window=lambda now=None: True)
|
||||||
|
for name in ("local_prices", "portwatch")
|
||||||
|
},
|
||||||
|
)
|
||||||
|
outcome = scheduler.run(names=["local_prices", "portwatch"], force=True)
|
||||||
|
assert outcome["status"] == "ok"
|
||||||
|
assert outcome["results"]["local_prices"]["status"] == "ok"
|
||||||
|
assert outcome["results"]["portwatch"]["status"] == "error"
|
||||||
|
assert "job_local_prices" not in str(outcome)
|
||||||
|
state = storage.job_get("local_prices")
|
||||||
|
assert state["status"] == "ok" and state["stored"] == 3
|
||||||
|
assert state["last_observation_at"] == "2026-09-12T18:00:00"
|
||||||
|
assert state["last_success_at"] and state["next_run_at"]
|
||||||
|
failed = storage.job_get("portwatch")
|
||||||
|
assert failed["status"] == "error" and failed["fail_count"] == 1
|
||||||
|
assert "OSError" in failed["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_inventory_exposes_source_frequency_state_and_next_run(store):
|
||||||
|
rows = {row["name"]: row for row in scheduler.inventory()}
|
||||||
|
assert rows["local_prices"]["source"].startswith("prix-carburants.gouv.fr")
|
||||||
|
assert rows["eu_bulletin"]["frequency"].startswith("le jeudi")
|
||||||
|
assert rows["promotions"]["status"] == "never"
|
||||||
|
assert rows["dgec_monthly"]["next_run_at"]
|
||||||
|
assert "n’historise un événement" in rows["local_prices"]["note"]
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch)."""
|
"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch)."""
|
||||||
|
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import zipfile
|
import zipfile
|
||||||
@@ -22,89 +23,139 @@ def make_xlsx(sheet_name, cells, strings=None):
|
|||||||
|
|
||||||
sheet_rows = {}
|
sheet_rows = {}
|
||||||
for ref in list(numeric) + list(text_values):
|
for ref in list(numeric) + list(text_values):
|
||||||
row = ''.join(ch for ch in ref if ch.isdigit())
|
row = "".join(ch for ch in ref if ch.isdigit())
|
||||||
sheet_rows.setdefault(int(row), []).append(cell_xml(ref, {**numeric, **text_values}[ref]))
|
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()))
|
body = "".join(
|
||||||
shared_xml = ('<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
f'<row r="{number}">{"".join(cells_xml)}</row>' for number, cells_xml in sorted(sheet_rows.items())
|
||||||
+ ''.join(f'<si><t>{value}</t></si>' for value in shared) + '</sst>')
|
)
|
||||||
workbook = ('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
|
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">'
|
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||||
f'<sheets><sheet name="{sheet_name}" sheetId="1" r:id="rId1"/></sheets></workbook>')
|
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>')
|
rels = (
|
||||||
sheet = ('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||||
f'<sheetData>{body}</sheetData></worksheet>')
|
'<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()
|
buffer = io.BytesIO()
|
||||||
with zipfile.ZipFile(buffer, 'w') as archive:
|
with zipfile.ZipFile(buffer, "w") as archive:
|
||||||
archive.writestr('xl/workbook.xml', workbook)
|
archive.writestr("xl/workbook.xml", workbook)
|
||||||
archive.writestr('xl/_rels/workbook.xml.rels', rels)
|
archive.writestr("xl/_rels/workbook.xml.rels", rels)
|
||||||
archive.writestr('xl/sharedStrings.xml', shared_xml)
|
archive.writestr("xl/sharedStrings.xml", shared_xml)
|
||||||
archive.writestr('xl/worksheets/sheet1.xml', sheet)
|
archive.writestr("xl/worksheets/sheet1.xml", sheet)
|
||||||
return buffer.getvalue()
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
def test_excel_date_conversion_and_rejection():
|
def test_excel_date_conversion_and_rejection():
|
||||||
assert upstream.excel_date(42005) == '2015-01-01'
|
assert upstream.excel_date(42005) == "2015-01-01"
|
||||||
assert upstream.excel_date(46272) == '2026-09-07'
|
assert upstream.excel_date(46272) == "2026-09-07"
|
||||||
assert upstream.excel_date('2025') is None
|
assert upstream.excel_date("2025") is None
|
||||||
assert upstream.excel_date(None) is None
|
assert upstream.excel_date(None) is None
|
||||||
|
|
||||||
|
|
||||||
def test_parse_dgec_brent_keeps_monthly_rows_only():
|
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})
|
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)
|
out = upstream.parse_dgec_brent(raw)
|
||||||
assert out == [{'day': '2015-01-01', 'value': 47.71}, {'day': '2015-02-01', 'value': 58.1}]
|
assert out == [{"day": "2015-01-01", "value": 47.71}, {"day": "2015-02-01", "value": 58.1}]
|
||||||
|
|
||||||
|
|
||||||
def test_parse_dgec_brent_rejects_garbage():
|
def test_parse_dgec_brent_rejects_garbage():
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
upstream.parse_dgec_brent(make_xlsx('Cours du Brent', {'B1': 'rien'}))
|
upstream.parse_dgec_brent(make_xlsx("Cours du Brent", {"B1": "rien"}))
|
||||||
|
|
||||||
|
|
||||||
def test_parse_dgec_margin_keeps_both_units():
|
def test_parse_dgec_margin_keeps_both_units():
|
||||||
raw = make_xlsx('Marge brute raffinage sur Brent', {'A3': 42005, 'B3': 6.9877, 'C3': 45.253})
|
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}]
|
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():
|
def test_parse_dgec_prices_splits_htt_and_ttc():
|
||||||
cells = {'A3': 46272, 'B2': 'Gazole', 'H2': 'Gazole', 'B3': 1.653, 'H3': 1.99}
|
cells = {"A3": 46272, "B2": "Gazole", "H2": "Gazole", "B3": 1.653, "H3": 1.99}
|
||||||
out = upstream.parse_dgec_prices(make_xlsx('Carburants routiers', cells))
|
out = upstream.parse_dgec_prices(make_xlsx("Carburants routiers", cells))
|
||||||
assert out == [{'day': '2026-09-07', 'htt': {'Gazole': 1.653}, 'ttc': {'Gazole': 1.99}}]
|
assert out == [{"day": "2026-09-07", "htt": {"Gazole": 1.653}, "ttc": {"Gazole": 1.99}}]
|
||||||
|
|
||||||
|
|
||||||
def test_parse_eu_bulletin_converts_thousands_of_litres():
|
def test_parse_eu_bulletin_converts_thousands_of_litres():
|
||||||
cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_with_tax_diesel', 'CN4': 2041.66,
|
cells = {
|
||||||
'CO1': 'FR_price_with_tax_euro95', 'CO4': 1899.99}
|
"A3": "Date",
|
||||||
out = upstream.parse_eu_bulletin(make_xlsx('Prices with taxes', cells))
|
"A4": 46272,
|
||||||
assert out == [{'day': '2026-09-07', 'prices': {'diesel': 2.042, 'euro95': 1.9}}]
|
"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():
|
def test_parse_eu_bulletin_accepts_without_tax_sheet():
|
||||||
# Le bulletin nomme le second onglet « Prices wo taxes » : les en-têtes diffèrent.
|
# 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}
|
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')
|
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}}]
|
assert out == [{"day": "2026-09-07", "prices": {"diesel": 1.5}}]
|
||||||
|
|
||||||
|
|
||||||
def test_parse_eu_bulletin_rejects_missing_country():
|
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})
|
raw = make_xlsx(
|
||||||
|
"Prices with taxes", {"A3": "Date", "A4": 46272, "CN1": "BE_price_with_tax_diesel", "CN4": 1500}
|
||||||
|
)
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
upstream.parse_eu_bulletin(raw)
|
upstream.parse_eu_bulletin(raw)
|
||||||
|
|
||||||
|
|
||||||
def test_parse_chokepoints_keeps_latest_per_watched_strait():
|
def test_parse_chokepoints_keeps_latest_per_watched_strait():
|
||||||
payload = json.dumps({'features': [
|
payload = json.dumps(
|
||||||
{'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,
|
"features": [
|
||||||
'capacity_tanker': 60280, 'capacity': 150000}},
|
{
|
||||||
{'attributes': {'date': '2026-09-06', 'portname': 'Bab el-Mandeb Strait', 'n_tanker': 6, 'n_total': 23}},
|
"attributes": {
|
||||||
{'attributes': {'date': '2026-09-06', 'portname': 'Port of Nantes', 'n_tanker': 99}},
|
"date": "2026-08-30",
|
||||||
]}).encode()
|
"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)
|
out = upstream.parse_chokepoints(payload)
|
||||||
assert set(out) == {'Strait of Hormuz', 'Bab el-Mandeb Strait'}
|
assert set(out) == {"Strait of Hormuz", "Bab el-Mandeb Strait"}
|
||||||
assert out['Strait of Hormuz']['day'] == '2026-09-06'
|
assert out["Strait of Hormuz"]["day"] == "2026-09-06"
|
||||||
assert out['Strait of Hormuz']['transit_tankers'] == 2
|
assert out["Strait of Hormuz"]["transit_tankers"] == 2
|
||||||
assert out['Strait of Hormuz']['capacity_total'] == 150000
|
assert out["Strait of Hormuz"]["capacity_total"] == 150000
|
||||||
|
|
||||||
|
|
||||||
def test_parse_chokepoints_rejects_garbage():
|
def test_parse_chokepoints_rejects_garbage():
|
||||||
@@ -113,7 +164,11 @@ def test_parse_chokepoints_rejects_garbage():
|
|||||||
|
|
||||||
|
|
||||||
def test_freshness_never_assumes_current():
|
def test_freshness_never_assumes_current():
|
||||||
assert upstream.freshness('2026-09-10', today=__import__('datetime').date(2026, 9, 12)) == {
|
assert upstream.freshness("2026-09-10", today=__import__("datetime").date(2026, 9, 12)) == {
|
||||||
'state': 'fresh', 'age_days': 2}
|
"state": "fresh",
|
||||||
assert upstream.freshness('2026-07-01', today=__import__('datetime').date(2026, 9, 12))['state'] == 'stale'
|
"age_days": 2,
|
||||||
assert upstream.freshness(None) == {'state': 'unknown', 'age_days': None}
|
}
|
||||||
|
assert (
|
||||||
|
upstream.freshness("2026-07-01", today=__import__("datetime").date(2026, 9, 12))["state"] == "stale"
|
||||||
|
)
|
||||||
|
assert upstream.freshness(None) == {"state": "unknown", "age_days": None}
|
||||||
|
|||||||
@@ -92,7 +92,6 @@ def test_collect_upstream_reports_total_failure(store):
|
|||||||
|
|
||||||
|
|
||||||
def test_collect_still_returns_no_favorites_with_upstream(store, monkeypatch):
|
def test_collect_still_returns_no_favorites_with_upstream(store, monkeypatch):
|
||||||
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
|
|
||||||
out = collector.collect(lambda: [], force=True)
|
out = collector.collect(lambda: [], force=True)
|
||||||
assert out["status"] == "no_favorites"
|
assert out["status"] == "no_favorites"
|
||||||
assert "upstream" in out
|
assert "upstream" in out
|
||||||
|
|||||||
27
ui.js
27
ui.js
@@ -90,15 +90,36 @@ function stationCards(rows){
|
|||||||
}
|
}
|
||||||
function render(d){
|
function render(d){
|
||||||
const s=d.local_stats||{},h=d.history||{};
|
const s=d.local_stats||{},h=d.history||{};
|
||||||
|
const fresh=d.local_refresh&&d.local_refresh.refreshed?`<span class="badge">Flux actualisé à l’instant</span>`:(d.local_refresh&&Number.isFinite(d.local_refresh.age_seconds)?`<span class="badge">Flux lu il y a ${num(d.local_refresh.age_seconds/60,0)} min</span>`:'');
|
||||||
const stations=(d.stations||[]).map(s=>`<div class="station"><div>${s.brand?`<span class="badge brand">${esc(s.brand)}</span>`:'<span class="badge">Enseigne inconnue</span>'}${s.road?`<span class="badge">${esc(s.road)}</span>`:''}<strong>${esc(s.name)}</strong><p class="hint">${esc(s.city)} · ${num(s.distance_km,1)} km à vol d’oiseau</p><p class="hint">Déclaré : ${esc(s.updated)}</p></div><div class="price">${num(s.price,3)} <small>€/L</small></div></div>`).join('');
|
const stations=(d.stations||[]).map(s=>`<div class="station"><div>${s.brand?`<span class="badge brand">${esc(s.brand)}</span>`:'<span class="badge">Enseigne inconnue</span>'}${s.road?`<span class="badge">${esc(s.road)}</span>`:''}<strong>${esc(s.name)}</strong><p class="hint">${esc(s.city)} · ${num(s.distance_km,1)} km à vol d’oiseau</p><p class="hint">Déclaré : ${esc(s.updated)}</p></div><div class="price">${num(s.price,3)} <small>€/L</small></div></div>`).join('');
|
||||||
const reasons=d.reasons.map(r=>`<li>${esc(r)}</li>`).join('');
|
const reasons=d.reasons.map(r=>`<li>${esc(r)}</li>`).join('');
|
||||||
const metrics=d.usable_km!==null?`<div class="metrics"><div class="metric"><strong>${num(d.usable_km)} km</strong><span>avant votre marge</span></div><div class="metric"><strong>${d.days_left===null?'Occasionnel':num(d.days_left,1)+' j'}</strong><span>${d.days_left===null?'pas de moyenne imposée':'usage moyen estimé'}</span></div><div class="metric"><strong>${d.topup_liters===null?'—':num(d.topup_liters,1)+' L'}</strong><span>appoint indicatif</span></div></div>`:'';
|
const metrics=d.usable_km!==null?`<div class="metrics"><div class="metric"><strong>${num(d.usable_km)} km</strong><span>avant votre marge</span></div><div class="metric"><strong>${d.days_left===null?'Occasionnel':num(d.days_left,1)+' j'}</strong><span>${d.days_left===null?'pas de moyenne imposée':'usage moyen estimé'}</span></div><div class="metric"><strong>${d.topup_liters===null?'—':num(d.topup_liters,1)+' L'}</strong><span>appoint indicatif</span></div></div>`:'';
|
||||||
$('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>
|
$('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>${fresh}</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">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"><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"><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>`;
|
<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()}${promotionsBlock(d.promotions,d.promotions_note)}<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));
|
status('Conseil calculé à '+stamp(d.generated_at));
|
||||||
}
|
}
|
||||||
|
const JOB_STATE={ok:['ok','tone-none'],unchanged:['sans changement','muted'],error:['échec','tone-refuel'],never:['jamais exécuté','muted'],'not_due':['non dû','muted']};
|
||||||
|
async function loadJobs(){
|
||||||
|
const box=$('jobs-list');box.textContent='Chargement…';
|
||||||
|
try{
|
||||||
|
const data=await api('/api/jobs');
|
||||||
|
box.innerHTML=data.jobs.map(job=>{
|
||||||
|
const [label,tone]=JOB_STATE[job.status]||JOB_STATE.never;
|
||||||
|
return `<div class="item"><div class="job-head"><strong>${esc(job.name)}</strong><span class="badge ${tone}">${label}</span></div>
|
||||||
|
<p class="hint">${esc(job.source)}</p>
|
||||||
|
<p class="hint">Fréquence : ${esc(job.frequency)}${job.note?` · ${esc(job.note)}`:''}</p>
|
||||||
|
<p class="hint">Dernière exécution réussie : ${job.last_success_at?stamp(job.last_success_at):'—'} · dernière observation disponible : ${job.last_observation_at?esc(String(job.last_observation_at).replace('T',' ')):'—'}</p>
|
||||||
|
<p class="hint">Prochaine exécution : ${job.next_run_at?stamp(job.next_run_at):'—'} · ${job.run_count} exécution(s) · ${job.fail_count} échec(s)${job.stored?` · ${job.stored} valeur(s)`:''}</p>
|
||||||
|
${job.detail?`<p class="hint">${esc(job.detail)}</p>`:''}</div>`;}).join('');
|
||||||
|
}catch(e){box.innerHTML='<p class="error">'+esc(e.message)+'</p>';}
|
||||||
|
}
|
||||||
|
function promotionsBlock(rows,note){
|
||||||
|
if(!rows?.length)return '';
|
||||||
|
const items=rows.map(p=>`<div class="station"><div><strong>${esc(p.brand)}</strong><p class="hint">${esc(p.nature.replace('_',' '))}${p.discount_per_liter?` · ${num(p.discount_per_liter,3)} €/L`:''}${p.fuels?` · ${esc(p.fuels)}`:''} · ${esc(p.state)}</p><p class="hint">${p.valid_from?`du ${esc(p.valid_from)}`:''}${p.valid_until?` au ${esc(p.valid_until)}`:''}${p.stations?` · ${esc(p.stations)}`:''}</p><p class="hint">${esc(p.source_url)} · confiance ${p.confidence!==null&&p.confidence!==undefined?num(p.confidence*100,0)+' %':'—'}</p></div></div>`).join('');
|
||||||
|
return `<h3>Opérations commerciales</h3><div>${items}</div><p class="hint">${esc(note||'')}</p>`;
|
||||||
|
}
|
||||||
function basePayload(){if(!coords)throw new Error('Choisissez d’abord un lieu.');return {...coords,radius_km:Number($('radius').value),fuel:$('fuel').value};}
|
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={}){
|
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>';
|
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>';
|
||||||
@@ -124,6 +145,8 @@ function bind(){
|
|||||||
$('trip-mode').onchange=()=>{const planned=$('trip-mode').value==='planned';$('trip-details').hidden=!planned;$('range-form').elements.trip_date.required=planned;$('range-form').elements.trip_km.required=planned;};
|
$('trip-mode').onchange=()=>{const planned=$('trip-mode').value==='planned';$('trip-details').hidden=!planned;$('range-form').elements.trip_date.required=planned;$('range-form').elements.trip_km.required=planned;};
|
||||||
$('range-form').onsubmit=e=>{e.preventDefault();const f=e.target,v=vehicle();if(!v)return;const extra={vehicle_id:v.id,remaining_km:Number(f.elements.remaining_km.value)};if(v.usage==='occasional'&&$('trip-mode').value==='planned')extra.trip={date:f.elements.trip_date.value,km:Number(f.elements.trip_km.value)};$('range-dialog').close();f.reset();calculate(extra);};
|
$('range-form').onsubmit=e=>{e.preventDefault();const f=e.target,v=vehicle();if(!v)return;const extra={vehicle_id:v.id,remaining_km:Number(f.elements.remaining_km.value)};if(v.usage==='occasional'&&$('trip-mode').value==='planned')extra.trip={date:f.elements.trip_date.value,km:Number(f.elements.trip_km.value)};$('range-dialog').close();f.reset();calculate(extra);};
|
||||||
$('range-dialog').addEventListener('close',()=>{$('range-form').reset();});
|
$('range-dialog').addEventListener('close',()=>{$('range-form').reset();});
|
||||||
|
$('diagnostic').onclick=async()=>{$('jobs-dialog').showModal();await loadJobs();};
|
||||||
|
$('jobs-refresh').onclick=loadJobs;
|
||||||
$('manage-vehicles').onclick=()=>{$('vehicles-dialog').showModal();};$('manage-favorites').onclick=()=>{$('favorites-dialog').showModal();};
|
$('manage-vehicles').onclick=()=>{$('vehicles-dialog').showModal();};$('manage-favorites').onclick=()=>{$('favorites-dialog').showModal();};
|
||||||
$('new-vehicle').onclick=()=>{fillForm($('vehicle-form'),{id:'',min_range_km:80,monthly_km:1000});$('vehicle-form-title').textContent='Ajouter un véhicule';usageChanged();};
|
$('new-vehicle').onclick=()=>{fillForm($('vehicle-form'),{id:'',min_range_km:80,monthly_km:1000});$('vehicle-form-title').textContent='Ajouter un véhicule';usageChanged();};
|
||||||
$('vehicle-form').elements.usage.onchange=usageChanged;
|
$('vehicle-form').elements.usage.onchange=usageChanged;
|
||||||
|
|||||||
219
upstream.py
219
upstream.py
@@ -3,6 +3,7 @@
|
|||||||
Aucune clé d'API. Aucune donnée inventée : une source absente reste absente et est signalée
|
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.
|
avec sa fraîcheur. Les parseurs sont purs (ils reçoivent des octets) pour rester testables.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import io
|
import io
|
||||||
@@ -14,32 +15,40 @@ import zipfile
|
|||||||
from datetime import date, datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
from xml.etree import ElementTree as ET
|
from xml.etree import ElementTree as ET
|
||||||
|
|
||||||
NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
|
||||||
USER_AGENT = (
|
USER_AGENT = (
|
||||||
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36'
|
"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)
|
EXCEL_EPOCH = datetime(1899, 12, 30)
|
||||||
|
|
||||||
DGEC_BASE = 'https://www.ecologie.gouv.fr/sites/default/files/documents/'
|
DGEC_BASE = "https://www.ecologie.gouv.fr/sites/default/files/documents/"
|
||||||
DGEC_FILES = {
|
DGEC_FILES = {
|
||||||
'brent': 'Historique%20du%20cours%20du%20Brent%20depuis%202015%20%28moyennes%20mensuelles%29_0.xlsx',
|
"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'
|
"margin": (
|
||||||
'%20%28moyennes%20mensuelles%29.xlsx'),
|
"Historique%20de%20la%20marge%20brute%20de%20raffinage%20sur%20Brent%20depuis%202015"
|
||||||
'prices': 'Prix%20HTT%20et%20TTC%20depuis%20janvier%202020_0.xlsx',
|
"%20%28moyennes%20mensuelles%29.xlsx"
|
||||||
|
),
|
||||||
|
"prices": "Prix%20HTT%20et%20TTC%20depuis%20janvier%202020_0.xlsx",
|
||||||
}
|
}
|
||||||
FUEL_COLUMNS = {
|
FUEL_COLUMNS = {
|
||||||
'Gazole': 'Gazole', 'SP95': 'Super SP95-E5', 'E10': 'Super SP95-E10',
|
"Gazole": "Gazole",
|
||||||
'SP98': 'Super SP98', 'E85': 'Superéthanol E85', 'GPLc': 'GPLc',
|
"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_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'}
|
EU_FUELS = {"Gazole": "diesel", "SP95": "euro95", "SP98": "euro98", "E10": "euro95", "E85": "euro95"}
|
||||||
PORTWATCH_QUERY = ('https://services9.arcgis.com/weJ1QsnbMYJlCHdG/arcgis/rest/services/'
|
PORTWATCH_QUERY = (
|
||||||
'Daily_Chokepoints_Data/FeatureServer/0/query')
|
"https://services9.arcgis.com/weJ1QsnbMYJlCHdG/arcgis/rest/services/"
|
||||||
WATCHED_CHOKEPOINTS = ('Strait of Hormuz', 'Bab el-Mandeb Strait', 'Suez Canal', 'Malacca Strait')
|
"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):
|
def fetch_bytes(url, timeout=60, limit=12_000_000):
|
||||||
request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT, 'Accept': '*/*'})
|
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "*/*"})
|
||||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||||
return response.read(limit)
|
return response.read(limit)
|
||||||
|
|
||||||
@@ -58,28 +67,30 @@ def excel_date(serial):
|
|||||||
def xlsx_cells(raw, sheet=None):
|
def xlsx_cells(raw, sheet=None):
|
||||||
"""Cellules {'A1': valeur} d'une feuille, valeurs partagées résolues."""
|
"""Cellules {'A1': valeur} d'une feuille, valeurs partagées résolues."""
|
||||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||||
workbook = archive.read('xl/workbook.xml').decode('utf-8', 'replace')
|
workbook = archive.read("xl/workbook.xml").decode("utf-8", "replace")
|
||||||
rels = archive.read('xl/_rels/workbook.xml.rels').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))
|
targets = dict(re.findall(r'Id="(rId\d+)"[^>]*Target="([^"]+)"', rels))
|
||||||
sheets = dict((name, targets.get(rid)) for name, rid in
|
sheets = dict(
|
||||||
re.findall(r'<sheet[^>]*name="([^"]+)"[^>]*r:id="(rId\d+)"', workbook))
|
(name, targets.get(rid))
|
||||||
|
for name, rid in re.findall(r'<sheet[^>]*name="([^"]+)"[^>]*r:id="(rId\d+)"', workbook)
|
||||||
|
)
|
||||||
if not sheets:
|
if not sheets:
|
||||||
raise ValueError('classeur sans feuille')
|
raise ValueError("classeur sans feuille")
|
||||||
name = sheet if sheet in sheets else next(iter(sheets))
|
name = sheet if sheet in sheets else next(iter(sheets))
|
||||||
strings = []
|
strings = []
|
||||||
if 'xl/sharedStrings.xml' in archive.namelist():
|
if "xl/sharedStrings.xml" in archive.namelist():
|
||||||
root = ET.fromstring(archive.read('xl/sharedStrings.xml'))
|
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
|
||||||
strings = [''.join(node.text or '' for node in item.iter()) for item in root]
|
strings = ["".join(node.text or "" for node in item.iter()) for item in root]
|
||||||
sheet_xml = ET.fromstring(archive.read('xl/' + sheets[name].lstrip('/')))
|
sheet_xml = ET.fromstring(archive.read("xl/" + sheets[name].lstrip("/")))
|
||||||
cells = {}
|
cells = {}
|
||||||
for cell in sheet_xml.iter(NS + 'c'):
|
for cell in sheet_xml.iter(NS + "c"):
|
||||||
value = cell.find(NS + 'v')
|
value = cell.find(NS + "v")
|
||||||
if value is None or value.text is None:
|
if value is None or value.text is None:
|
||||||
continue
|
continue
|
||||||
reference = cell.attrib.get('r', '')
|
reference = cell.attrib.get("r", "")
|
||||||
if not reference:
|
if not reference:
|
||||||
continue
|
continue
|
||||||
cells[reference] = strings[int(value.text)] if cell.attrib.get('t') == 's' else value.text
|
cells[reference] = strings[int(value.text)] if cell.attrib.get("t") == "s" else value.text
|
||||||
return cells
|
return cells
|
||||||
|
|
||||||
|
|
||||||
@@ -87,17 +98,17 @@ def column_headers(cells, row=1):
|
|||||||
"""En-têtes de la ligne ``row`` : {'CN': 'FR_price_with_tax_euro95'}."""
|
"""En-têtes de la ligne ``row`` : {'CN': 'FR_price_with_tax_euro95'}."""
|
||||||
out = {}
|
out = {}
|
||||||
for reference, value in cells.items():
|
for reference, value in cells.items():
|
||||||
match = re.fullmatch(r'([A-Z]{1,3})%d' % row, reference)
|
match = re.fullmatch(r"([A-Z]{1,3})%d" % row, reference)
|
||||||
if match and isinstance(value, str):
|
if match and isinstance(value, str):
|
||||||
out[match.group(1)] = value
|
out[match.group(1)] = value
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _rows_by_date(cells, date_column='A', first_row=4):
|
def _rows_by_date(cells, date_column="A", first_row=4):
|
||||||
"""Associe chaque ligne à sa date ISO via la colonne de dates."""
|
"""Associe chaque ligne à sa date ISO via la colonne de dates."""
|
||||||
out = {}
|
out = {}
|
||||||
for reference, value in cells.items():
|
for reference, value in cells.items():
|
||||||
match = re.fullmatch(re.escape(date_column) + r'(\d+)', reference)
|
match = re.fullmatch(re.escape(date_column) + r"(\d+)", reference)
|
||||||
if not match:
|
if not match:
|
||||||
continue
|
continue
|
||||||
day = excel_date(value)
|
day = excel_date(value)
|
||||||
@@ -106,12 +117,12 @@ def _rows_by_date(cells, date_column='A', first_row=4):
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def parse_dgec_brent(raw, sheet='Cours du Brent'):
|
def parse_dgec_brent(raw, sheet="Cours du Brent"):
|
||||||
"""Cours moyen mensuel du Brent daté (DGEC, $/baril), lignes annuelles écartées."""
|
"""Cours moyen mensuel du Brent daté (DGEC, $/baril), lignes annuelles écartées."""
|
||||||
cells = xlsx_cells(raw, sheet)
|
cells = xlsx_cells(raw, sheet)
|
||||||
out = []
|
out = []
|
||||||
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
|
for row, day in sorted(_rows_by_date(cells, "A", 3).items()):
|
||||||
value = cells.get('B%d' % row)
|
value = cells.get("B%d" % row)
|
||||||
try:
|
try:
|
||||||
price = float(value)
|
price = float(value)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
@@ -119,98 +130,101 @@ def parse_dgec_brent(raw, sheet='Cours du Brent'):
|
|||||||
if 5 <= price <= 400:
|
if 5 <= price <= 400:
|
||||||
out.append(dict(day=day, value=round(price, 2)))
|
out.append(dict(day=day, value=round(price, 2)))
|
||||||
if not out:
|
if not out:
|
||||||
raise ValueError('cours du Brent illisible')
|
raise ValueError("cours du Brent illisible")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def parse_dgec_margin(raw, sheet='Marge brute raffinage sur Brent'):
|
def parse_dgec_margin(raw, sheet="Marge brute raffinage sur Brent"):
|
||||||
"""Marge brute de raffinage sur Brent (DGEC) en $/baril et en €/tonne."""
|
"""Marge brute de raffinage sur Brent (DGEC) en $/baril et en €/tonne."""
|
||||||
cells = xlsx_cells(raw, sheet)
|
cells = xlsx_cells(raw, sheet)
|
||||||
out = []
|
out = []
|
||||||
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
|
for row, day in sorted(_rows_by_date(cells, "A", 3).items()):
|
||||||
try:
|
try:
|
||||||
usd = float(cells.get('B%d' % row))
|
usd = float(cells.get("B%d" % row))
|
||||||
eur = float(cells.get('C%d' % row))
|
eur = float(cells.get("C%d" % row))
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
continue
|
continue
|
||||||
if -20 <= usd <= 100 and -100 <= eur <= 800:
|
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)))
|
out.append(dict(day=day, usd_per_bbl=round(usd, 2), eur_per_tonne=round(eur, 2)))
|
||||||
if not out:
|
if not out:
|
||||||
raise ValueError('marge de raffinage illisible')
|
raise ValueError("marge de raffinage illisible")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def parse_dgec_prices(raw, sheet='Carburants routiers'):
|
def parse_dgec_prices(raw, sheet="Carburants routiers"):
|
||||||
"""Prix moyens français HTT et TTC par carburant (DGEC)."""
|
"""Prix moyens français HTT et TTC par carburant (DGEC)."""
|
||||||
cells = xlsx_cells(raw, sheet)
|
cells = xlsx_cells(raw, sheet)
|
||||||
headers = column_headers(cells, 2)
|
headers = column_headers(cells, 2)
|
||||||
htt = {letter: name for letter, name in headers.items() if letter < 'H'}
|
htt = {letter: name for letter, name in headers.items() if letter < "H"}
|
||||||
ttc = {letter: name for letter, name in headers.items() if letter >= 'H'}
|
ttc = {letter: name for letter, name in headers.items() if letter >= "H"}
|
||||||
out = []
|
out = []
|
||||||
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
|
for row, day in sorted(_rows_by_date(cells, "A", 3).items()):
|
||||||
entry = dict(day=day, htt={}, ttc={})
|
entry = dict(day=day, htt={}, ttc={})
|
||||||
for letter, name in htt.items():
|
for letter, name in htt.items():
|
||||||
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
|
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
|
||||||
try:
|
try:
|
||||||
entry['htt'][fuel] = round(float(cells['%s%d' % (letter, row)]), 3)
|
entry["htt"][fuel] = round(float(cells["%s%d" % (letter, row)]), 3)
|
||||||
except (KeyError, TypeError, ValueError):
|
except (KeyError, TypeError, ValueError):
|
||||||
continue
|
continue
|
||||||
for letter, name in ttc.items():
|
for letter, name in ttc.items():
|
||||||
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
|
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
|
||||||
try:
|
try:
|
||||||
entry['ttc'][fuel] = round(float(cells['%s%d' % (letter, row)]), 3)
|
entry["ttc"][fuel] = round(float(cells["%s%d" % (letter, row)]), 3)
|
||||||
except (KeyError, TypeError, ValueError):
|
except (KeyError, TypeError, ValueError):
|
||||||
continue
|
continue
|
||||||
if entry['htt'] or entry['ttc']:
|
if entry["htt"] or entry["ttc"]:
|
||||||
out.append(entry)
|
out.append(entry)
|
||||||
if not out:
|
if not out:
|
||||||
raise ValueError('prix HTT/TTC illisibles')
|
raise ValueError("prix HTT/TTC illisibles")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def parse_eu_bulletin(raw, country='FR', sheet='Prices with taxes'):
|
def parse_eu_bulletin(raw, country="FR", sheet="Prices with taxes"):
|
||||||
"""Prix hebdomadaires par pays du bulletin pétrolier UE (€/1000 L -> €/L)."""
|
"""Prix hebdomadaires par pays du bulletin pétrolier UE (€/1000 L -> €/L)."""
|
||||||
cells = xlsx_cells(raw, sheet)
|
cells = xlsx_cells(raw, sheet)
|
||||||
headers = column_headers(cells, 1)
|
headers = column_headers(cells, 1)
|
||||||
columns = {}
|
columns = {}
|
||||||
for letter, name in headers.items():
|
for letter, name in headers.items():
|
||||||
match = re.fullmatch(re.escape(country) + r'_price_(?:with_tax|wo_tax|without_tax)_(\w+)', name)
|
match = re.fullmatch(re.escape(country) + r"_price_(?:with_tax|wo_tax|without_tax)_(\w+)", name)
|
||||||
if match:
|
if match:
|
||||||
columns[letter] = match.group(1)
|
columns[letter] = match.group(1)
|
||||||
if not columns:
|
if not columns:
|
||||||
raise ValueError(f'pays {country} absent du bulletin')
|
raise ValueError(f"pays {country} absent du bulletin")
|
||||||
out = []
|
out = []
|
||||||
for row, day in sorted(_rows_by_date(cells, 'A', 4).items()):
|
for row, day in sorted(_rows_by_date(cells, "A", 4).items()):
|
||||||
entry = dict(day=day, prices={})
|
entry = dict(day=day, prices={})
|
||||||
for letter, product in columns.items():
|
for letter, product in columns.items():
|
||||||
try:
|
try:
|
||||||
entry['prices'][product] = round(float(cells['%s%d' % (letter, row)]) / 1000, 3)
|
entry["prices"][product] = round(float(cells["%s%d" % (letter, row)]) / 1000, 3)
|
||||||
except (KeyError, TypeError, ValueError):
|
except (KeyError, TypeError, ValueError):
|
||||||
continue
|
continue
|
||||||
if entry['prices']:
|
if entry["prices"]:
|
||||||
out.append(entry)
|
out.append(entry)
|
||||||
if not out:
|
if not out:
|
||||||
raise ValueError('aucune semaine exploitable')
|
raise ValueError("aucune semaine exploitable")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def parse_chokepoints(payload):
|
def parse_chokepoints(payload):
|
||||||
"""Dernière valeur connue par détroit surveillé (source IMF PortWatch)."""
|
"""Dernière valeur connue par détroit surveillé (source IMF PortWatch)."""
|
||||||
try:
|
try:
|
||||||
features = json.loads(payload)['features']
|
features = json.loads(payload)["features"]
|
||||||
except (KeyError, TypeError, ValueError):
|
except (KeyError, TypeError, ValueError):
|
||||||
raise ValueError('flux PortWatch illisible') from None
|
raise ValueError("flux PortWatch illisible") from None
|
||||||
latest = {}
|
latest = {}
|
||||||
for feature in features:
|
for feature in features:
|
||||||
attributes = feature.get('attributes') or {}
|
attributes = feature.get("attributes") or {}
|
||||||
name = attributes.get('portname')
|
name = attributes.get("portname")
|
||||||
day = str(attributes.get('date') or '')
|
day = str(attributes.get("date") or "")
|
||||||
if name not in WATCHED_CHOKEPOINTS or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', day):
|
if name not in WATCHED_CHOKEPOINTS or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
|
||||||
continue
|
continue
|
||||||
if name not in latest or day > latest[name]['day']:
|
if name not in latest or day > latest[name]["day"]:
|
||||||
latest[name] = dict(
|
latest[name] = dict(
|
||||||
day=day, transit_tankers=attributes.get('n_tanker'), transit_total=attributes.get('n_total'),
|
day=day,
|
||||||
capacity_tankers=attributes.get('capacity_tanker'), capacity_total=attributes.get('capacity'),
|
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
|
return latest
|
||||||
|
|
||||||
@@ -221,10 +235,10 @@ def freshness(day, today=None, max_age_days=10):
|
|||||||
try:
|
try:
|
||||||
age = (today - date.fromisoformat(day)).days
|
age = (today - date.fromisoformat(day)).days
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
return dict(state='unknown', age_days=None)
|
return dict(state="unknown", age_days=None)
|
||||||
if age < 0:
|
if age < 0:
|
||||||
return dict(state='unknown', age_days=age)
|
return dict(state="unknown", age_days=age)
|
||||||
return dict(state='fresh' if age <= max_age_days else 'stale', age_days=age)
|
return dict(state="fresh" if age <= max_age_days else "stale", age_days=age)
|
||||||
|
|
||||||
|
|
||||||
def dgec_urls():
|
def dgec_urls():
|
||||||
@@ -233,27 +247,76 @@ def dgec_urls():
|
|||||||
|
|
||||||
def eu_bulletin_url():
|
def eu_bulletin_url():
|
||||||
"""Le bulletin hebdomadaire est publié derrière une URL à identifiant variable."""
|
"""Le bulletin hebdomadaire est publié derrière une URL à identifiant variable."""
|
||||||
html = fetch_bytes(EU_BULLETIN_PAGE, timeout=45).decode('utf-8', 'replace')
|
html = fetch_bytes(EU_BULLETIN_PAGE, timeout=45).decode("utf-8", "replace")
|
||||||
links = re.findall(r'href="([^"]*filename=[^"]*\.xlsx)"', html, re.I)
|
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)]
|
history = [link for link in links if re.search(r"histor", urllib.parse.unquote(link), re.I)]
|
||||||
if not history:
|
if not history:
|
||||||
raise ValueError('fichier d’historique du bulletin introuvable')
|
raise ValueError("fichier d’historique du bulletin introuvable")
|
||||||
url = history[0].replace('&', '&')
|
url = history[0].replace("&", "&")
|
||||||
return url if url.startswith('http') else 'https://energy.ec.europa.eu' + url
|
return url if url.startswith("http") else "https://energy.ec.europa.eu" + url
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_chokepoint_window(days=12, today=None):
|
||||||
|
"""Fenêtre glissante : les révisions de PortWatch doivent mettre à jour les jours déjà connus."""
|
||||||
|
today = today or datetime.now(timezone.utc).date()
|
||||||
|
start = (today - timedelta(days=days)).isoformat()
|
||||||
|
query = urllib.parse.urlencode(
|
||||||
|
{
|
||||||
|
"where": f"date >= DATE '{start}' AND date <= DATE '{today.isoformat()}'",
|
||||||
|
"outFields": "*",
|
||||||
|
"returnGeometry": "false",
|
||||||
|
"orderByFields": "date ASC",
|
||||||
|
"resultRecordCount": "1000",
|
||||||
|
"f": "json",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
payload = fetch_bytes(f"{PORTWATCH_QUERY}?{query}", timeout=45)
|
||||||
|
try:
|
||||||
|
features = json.loads(payload)["features"]
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
raise ValueError("flux PortWatch illisible") from None
|
||||||
|
pairs = []
|
||||||
|
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
|
||||||
|
pairs.append(
|
||||||
|
(
|
||||||
|
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"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if not pairs:
|
||||||
|
raise ValueError("aucune donnée de détroit dans la fenêtre demandée")
|
||||||
|
return pairs
|
||||||
|
|
||||||
|
|
||||||
def fetch_chokepoints(days=6, today=None):
|
def fetch_chokepoints(days=6, today=None):
|
||||||
"""Détroits surveillés : quelques jours suffisent, la source a du retard."""
|
"""Détroits surveillés : quelques jours suffisent, la source a du retard."""
|
||||||
today = today or datetime.now(timezone.utc).date()
|
today = today or datetime.now(timezone.utc).date()
|
||||||
query = urllib.parse.urlencode({
|
query = urllib.parse.urlencode(
|
||||||
'where': f"date >= DATE '{today.isoformat()}'", 'outFields': '*',
|
{
|
||||||
'returnGeometry': 'false', 'orderByFields': 'date DESC', 'resultRecordCount': '200', 'f': 'json',
|
"where": f"date >= DATE '{today.isoformat()}'",
|
||||||
})
|
"outFields": "*",
|
||||||
|
"returnGeometry": "false",
|
||||||
|
"orderByFields": "date DESC",
|
||||||
|
"resultRecordCount": "200",
|
||||||
|
"f": "json",
|
||||||
|
}
|
||||||
|
)
|
||||||
for offset in range(days, days + 12, 6):
|
for offset in range(days, days + 12, 6):
|
||||||
lookback = (today - timedelta(days=offset)).isoformat()
|
lookback = (today - timedelta(days=offset)).isoformat()
|
||||||
probe = query.replace(urllib.parse.quote(today.isoformat()), urllib.parse.quote(lookback))
|
probe = query.replace(urllib.parse.quote(today.isoformat()), urllib.parse.quote(lookback))
|
||||||
payload = fetch_bytes(f'{PORTWATCH_QUERY}?{probe}', timeout=40)
|
payload = fetch_bytes(f"{PORTWATCH_QUERY}?{probe}", timeout=40)
|
||||||
found = parse_chokepoints(payload)
|
found = parse_chokepoints(payload)
|
||||||
if found:
|
if found:
|
||||||
return found, None
|
return found, None
|
||||||
return {}, 'PortWatch : aucune donnée récente (retard de publication ou service indisponible)'
|
return {}, "PortWatch : aucune donnée récente (retard de publication ou service indisponible)"
|
||||||
|
|||||||
Reference in New Issue
Block a user