diff --git a/README.md b/README.md index 111ac80..03b03b6 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,57 @@ 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. +## Distances routières et navigation + +Le rayon choisi porte sur la **distance routière réelle**, pas sur la distance à vol d'oiseau : + +1. préfiltre rapide à vol d'oiseau (facteur `FUEL_PREFILTER_FACTOR=1.6`) pour choisir les candidates ; +2. itinéraire réel une origine → N destinations, avec distance **et** durée ; +3. rayon appliqué à la distance routière, puis affichage : distance en voiture, durée, prix, enseigne. + +Fournisseurs, dans l'ordre configurable `FUEL_ROUTING_PROVIDERS` (défaut `osrm,google`) : + +- **OSRM public** (`https://router.project-osrm.org`) : gratuit, sans clé, ~0,1 s pour 60 destinations. + Remplaçable par une instance propre via `FUEL_OSRM_URL`. +- **Google Routes API** (`computeRouteMatrix`, origine unique vers N destinations) : nécessite une clé + et une facturation ; activée automatiquement si `FUEL_GOOGLE_MAPS_API_KEY` (ou `GOOGLE_MAPS_API_KEY`) + est présent. Sans clé, elle n'est jamais appelée. + +Aucun fournisseur joignable : l'application le dit, affiche les distances à vol d'oiseau et applique +le rayon à cette distance — elle n'invente jamais une distance routière. Une station sans itinéraire +calculable est exclue plutôt qu'estimée. + +Chaque station expose deux liens d'itinéraire construits sur ses coordonnées exactes : +Google Maps Directions (`https://www.google.com/maps/dir/?api=1&destination=…&travelmode=driving`) +et Waze Deep Link (`https://waze.com/ul?ll=…&navigate=yes`). + +Les couples (position, station) sont mis en cache 90 jours (`route_cache`) avec distance et durée : +de quoi calculer plus tard le **coût réel du détour** (gain sur le plein moins le carburant consommé). +Aucune décision n'est prise sur cette base pour l'instant. + +## Pression amont expliquée simplement + +`GET /api/advice` renvoie `upstream_synthesis` : verdict **HAUSSE / BAISSE / NEUTRE / INCERTAINE**, +confiance, puis 3 à 6 facteurs en langage courant (brut, euro/dollar, raffinage, produits raffinés, +Ormuz et détroits, géopolitique), chacun avec sa flèche ↑ ↓ → ?, son explication, la date et la source +de la donnée. Un paragraphe « En clair » résume ce que cela signifie pour un automobiliste et rappelle +qu'il ne s'agit **pas** d'une prévision validée du prix à la pompe. Les valeurs techniques, unités, +dates, fraîcheur et sources restent disponibles derrière « Afficher les données techniques ». + +Les poids (`FACTOR_WEIGHTS`) sont explicites et lisibles ; le verdict est un vote pondéré calculé, +jamais une appréciation d'un modèle. Ollama n'intervient pas dans ce calcul. + +## File d'analyse Ollama supervisée + +- **Préfiltrage déterministe** avant tout appel de modèle : lexique carburant/pétrole obligatoire, + doublons de titre écartés, articles de plus de `FUEL_NEWS_MAX_AGE_DAYS` (5) jours écartés. + Les articles écartés sont marqués (`news_articles.skip_reason`) et ne reviennent jamais. +- **Supervision** (`GET /api/jobs`, champ `llm_queue`, fenêtre Supervision) : nombre d'articles en + attente, âge du plus ancien, analysés sur 24 h, durée moyenne et maximale, échecs, répartition par + modèle, et nombre d'articles écartés par le préfiltrage. +- Durée mesurée : ~2–3 min par article avec `mistral-small3.2:24b`. L'ordre des modèles est + configurable (`FUEL_LLM_ORDER`) et un benchmark compare `gemma4:12b` au 24b sur le même jeu d'articles. + ## Ordonnanceur multi-fréquences Un seul point d'entrée, prévu **toutes les 10 minutes** dans `/etc/crontabs/root` : diff --git a/app.py b/app.py index 0668879..7aa2a17 100755 --- a/app.py +++ b/app.py @@ -24,8 +24,10 @@ import brands import collector import market import promotions +import routing import scheduler import storage +import synthesis from decision import recommend APP_DIR = Path(__file__).resolve().parent @@ -53,9 +55,23 @@ class Station: lon: float price: float updated: str - distance_km: float + distance_km: float # distance à vol d'oiseau : préfiltre interne road: str = "" brand: str | None = None + route_distance_km: float | None = None # distance routière réelle + route_duration_min: float | None = None # durée estimée en voiture + route_provider: str = "none" + navigation: dict | None = None # liens d'itinéraire (Google Maps, Waze) + + +def navigation_links(lat, lon): + """Liens officiels d'itinéraire vers une coordonnée exacte de station.""" + coords = f"{lat:.6f},{lon:.6f}" + return dict( + google_maps=f"https://www.google.com/maps/dir/?api=1&destination={coords}&travelmode=driving", + waze=f"https://waze.com/ul?ll={coords}&navigate=yes", + coordinates=coords, + ) def now_iso(): @@ -152,28 +168,80 @@ def load_fuel_data(force=False): haversine = storage.distance_km -def nearest_stations(lat, lon, fuel, radius_km): - stations = [] +def candidate_stations(lat, lon, fuel, radius_km): + """Préfiltre rapide à vol d'oiseau, volontairement plus large que le rayon demandé. + + La route est toujours plus longue que la ligne droite : ce préfiltre évite de calculer + un itinéraire pour des stations lointaines sans en écarter de plausibles. + """ + factor = float(os.environ.get("FUEL_PREFILTER_FACTOR", "1.6")) + candidates = [] for row in load_fuel_data(): if fuel not in row["prices"] or not storage.fresh_price(row["updates"].get(fuel, "")): continue - distance = haversine(lat, lon, row["lat"], row["lon"]) - if distance <= radius_km: - stations.append( - Station( - id=row["id"], - name=row["name"] or "Station-service", - address=row["address"], - city=row["city"], - lat=row["lat"], - lon=row["lon"], - price=row["prices"][fuel], - updated=row["updates"].get(fuel, ""), - distance_km=round(distance, 1), - road=row.get("road", ""), - ) + air = haversine(lat, lon, row["lat"], row["lon"]) + if air <= radius_km * factor: + candidates.append((row, air)) + candidates.sort(key=lambda item: item[1]) + limit = int(os.environ.get("FUEL_ROUTING_MAX_TARGETS", "60")) + return candidates[:limit] + + +def nearest_stations(lat, lon, fuel, radius_km, routing_enabled=True): + """Rayon appliqué à la **distance routière** ; le vol d'oiseau ne sert que de préfiltre.""" + candidates = candidate_stations(lat, lon, fuel, radius_km) + routes, routing_info = {}, dict(provider="none", computed=0, from_cache=0, failures=[], note="") + if candidates and routing_enabled: + try: + routes, routing_info = routing.routes( + (lat, lon), [(row["id"], row["lat"], row["lon"]) for row, _air in candidates]) + except Exception as exc: + LOG.warning("Calcul d'itinéraire impossible : %s", type(exc).__name__) + routing_info = dict(provider="none", computed=0, from_cache=0, failures=[type(exc).__name__], + note="Service de routage indisponible.") + stations = [] + for row, air in candidates: + route = routes.get(row["id"]) + if routes: + if not route: + continue # pas d'itinéraire connu : aucune distance approximée présentée + if route["distance_km"] > radius_km: + continue # le rayon porte bien sur la distance routière + elif air > radius_km: + continue # sans routage, repli explicite sur le vol d'oiseau (signalé à l'écran) + stations.append( + Station( + id=row["id"], + name=row["name"] or "Station-service", + address=row["address"], + city=row["city"], + lat=row["lat"], + lon=row["lon"], + price=row["prices"][fuel], + updated=row["updates"].get(fuel, ""), + distance_km=round(air, 1), + road=row.get("road", ""), + route_distance_km=route["distance_km"] if route else None, + route_duration_min=route["duration_min"] if route else None, + route_provider=route["provider"] if route else "none", + navigation=navigation_links(row["lat"], row["lon"]), ) - return sorted(stations, key=lambda s: (s.price, s.distance_km)) + ) + return sorted(stations, key=lambda s: (s.price, + s.route_distance_km if s.route_distance_km is not None + else s.distance_km)), routing_info + + +def _synthesis(fuel): + """Synthèse amont explicable ; une erreur de calcul ne doit jamais casser le conseil.""" + try: + return synthesis.build(fuel) + except Exception as exc: + LOG.warning("Synthèse amont indisponible : %s", type(exc).__name__) + return dict(pressure="INCERTAINE", pressure_key="unknown", confidence=None, factors=[], + plain="Synthèse indisponible : les données amont n’ont pas pu être lues.", + disclaimer="Aucun indicateur n’est utilisé faute de données exploitables.", + generated_at=now_iso(), error=type(exc).__name__) def market_signal(force=False): @@ -195,13 +263,14 @@ def geocode_address(query): 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"))) + 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__) + LOG.warning('Actualisation locale impossible : %s', type(exc).__name__) refresh = dict(refreshed=False, error=type(exc).__name__) stations, error = [], None + routing_info = dict(provider="none", computed=0, from_cache=0, failures=[], note="") try: - stations = nearest_stations(lat, lon, fuel, radius_km) + stations, routing_info = nearest_stations(lat, lon, fuel, radius_km) except Exception as exc: LOG.warning("Source des prix inaccessible : %s", type(exc).__name__) error = "Source des prix inaccessible ; aucun ancien prix présenté comme actuel." @@ -247,12 +316,27 @@ def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None price_warning=error or (None if prices else "Aucun prix déclaré depuis moins de 7 jours dans ce rayon."), 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.", + routing=routing_info, + distance_note=( + "Distances routières réelles en voiture, calculées depuis votre position" + + (f" (fournisseur {routing_info['provider']})" + if routing_info.get('provider') not in (None, 'none') else "") + + ". Le détour peut annuler l’économie." + if routing_info.get("provider") not in (None, "none") else + "Routage indisponible : les distances affichées restent à vol d’oiseau et le rayon " + "porte sur cette distance. Le détour peut annuler l’économie."), + detour_prep=dict( + available=any(s.route_distance_km is not None for s in stations), + note="Distance et durée routières enregistrées pour chaque station : de quoi calculer " + "plus tard le coût réel du détour (gain sur le plein moins le carburant consommé " + "pour y aller). Aucune décision n’est prise sur cette base pour l’instant.", + ), + upstream_synthesis=_synthesis(fuel), 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.", + "comparez son tarif estimé aux autres stations du rayon.", ) return result @@ -321,46 +405,25 @@ class Handler(BaseHTTPRequestHandler): if path == "/api/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.", - ) - ) + return self.send_json(dict( + jobs=scheduler.inventory(), + llm_queue=storage.llm_queue(), + 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.", - ) - ) + return self.send_json(dict(items=promotions.active()[:40], + note="Opérations annoncées ou en cours, avec leur source.")) if path == "/api/upstream": return self.send_json( - dict( - series=storage.latest_upstream(), - history={ - name: storage.upstream_series(name, int(q.get("days", 400))) - for name in ( - "dgec_brent_usd", - "brent_usd_daily", - "brent_eur_daily", - "usd_per_eur", - "dgec_margin_usd_per_bbl", - "dgec_margin_eur_per_tonne", - "fr_ttc_Gazole", - "fr_htt_Gazole", - "fr_ttc_E10", - "fr_htt_E10", - "eu_fr_diesel_ttc", - "eu_fr_diesel_htt", - ) - }, - chokepoints=storage.chokepoint_daily(int(q.get("chokepoint_days", 60))), - note="Sources amont officielles. Chaque valeur porte sa date et sa source ; " - "une donnée absente reste inconnue, jamais supposée stable.", - ) - ) + dict(series=storage.latest_upstream(), + history={name: storage.upstream_series(name, int(q.get("days", 400))) + for name in ("dgec_brent_usd", "brent_usd_daily", "brent_eur_daily", + "usd_per_eur", "dgec_margin_usd_per_bbl", "dgec_margin_eur_per_tonne", + "fr_ttc_Gazole", "fr_htt_Gazole", "fr_ttc_E10", "fr_htt_E10", + "eu_fr_diesel_ttc", "eu_fr_diesel_htt")}, + chokepoints=storage.chokepoint_daily(int(q.get("chokepoint_days", 60))), + note="Sources amont officielles. Chaque valeur porte sa date et sa source ; " + "une donnée absente reste inconnue, jamais supposée stable.")) if path in ("/api/vehicles", "/api/favorites"): return self.send_json(dict(items=storage.list_entities(path.split("/")[-1]))) if path == "/api/geocode": diff --git a/llm.py b/llm.py index 526d8d3..043a920 100644 --- a/llm.py +++ b/llm.py @@ -71,10 +71,20 @@ def generate(prompt, model=None, timeout=None, temperature=0): return parse_json(text), body.get("model") or model or PRIMARY_MODEL +def model_order(): + """Ordre réellement utilisé : lisible et modifiable sans toucher au code. + + Défaut : ``mistral-small3.2:24b`` puis ``gemma4:12b``. Le benchmark comparatif peut + inverser cet ordre via ``FUEL_LLM_ORDER``. + """ + configured = [name.strip() for name in os.environ.get("FUEL_LLM_ORDER", "").split(",") if name.strip()] + return tuple(configured) or (PRIMARY_MODEL, FALLBACK_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): + for model in models or model_order(): try: return generate(prompt, model=model, timeout=timeout) except Exception as exc: diff --git a/news.py b/news.py index c732064..bdb328d 100644 --- a/news.py +++ b/news.py @@ -12,6 +12,8 @@ import html import json import os import re +import time +import unicodedata import urllib.parse import urllib.request from datetime import date, datetime, timedelta, timezone @@ -23,6 +25,8 @@ import upstream USER_AGENT = upstream.USER_AGENT MAX_ARTICLES_PER_RUN = int(os.environ.get("FUEL_NEWS_MAX_PER_RUN", "3")) +# Au-delà de ce délai, un article n'éclaire plus la pression du moment : il n'est pas analysé. +MAX_AGE_DAYS = int(os.environ.get("FUEL_NEWS_MAX_AGE_DAYS", "5")) TOPICS = { "ormuz": ["détroit Ormuz pétrole", "Strait of Hormuz oil tanker"], @@ -53,6 +57,130 @@ Texte : {text} """ +def normalize(text): + """Minuscules sans accents : le préfiltrage doit être insensible à la typographie.""" + text = unicodedata.normalize("NFKD", str(text or "").lower()) + return "".join(char for char in text if not unicodedata.combining(char)) + + +# Lexique déterministe : un article sans aucun de ces termes ne part jamais vers un modèle. +FUEL_LEXICON = ( + "petrole", + "brut", + "baril", + "brent", + "wti", + "carburant", + "essence", + "gazole", + "diesel", + "raffin", + "ormuz", + "hormuz", + "suez", + "bab el-mandeb", + "bab-el-mandeb", + "mer rouge", + "opep", + "opec", + "sanction", + "embargo", + "greve", + "blocage", + "depot", + "accise", + "taxe carburant", + "pipeline", + "oleoduc", + "petrolier", + "tanker", + "chokepoint", + "detroit", + "prix a la pompe", + "station-service", + "prix coutant", + "remise carburant", + "fuel", + "oil", + "crude", + "refinery", + "strait", + "shipping", + "huile", + "gnv", + "gpl", + "e85", +) +# Termes qui doivent apparaître pour un article purement géopolitique : sans eux, l'article +# parle de pétrole sans qu'on puisse en tirer un effet plausible sur les prix en France. +STRONG_TERMS = ( + "petrole", + "carburant", + "gazole", + "diesel", + "raffin", + "brent", + "baril", + "opep", + "opec", + "ormuz", + "hormuz", + "suez", + "bab el-mandeb", + "sanction", + "embargo", + "greve", + "blocage", + "depot", + "accise", + "pipeline", + "oleoduc", + "tanker", + "petrolier", +) + + +def relevant(article, topic=None): + """Détermine, sans aucun modèle, si un article peut influencer les prix des carburants.""" + text = normalize(article.get("title", "") + " " + (article.get("summary") or "")) + strong = [term for term in STRONG_TERMS if term in text] + if not strong: + return False, "aucun terme carburant ou pétrole" + if not (article.get("summary") or "").strip() and len(normalize(article.get("title", ""))) < 20: + return False, "titre trop court, aucun contenu exploitable" + return True, "" + + +def is_stale(article, days=None): + """Un article trop ancien ne dit plus rien de la pression actuelle : il n'est pas analysé.""" + days = MAX_AGE_DAYS if days is None else days + stamp = article.get("published_at") or article.get("observed_at") or article.get("fetched_at") + if not stamp: + return False + try: + published = date.fromisoformat(str(stamp)[:10]) + except ValueError: + return False + return (datetime.now(timezone.utc).date() - published).days > days + + +def prefilter(articles): + """Sépare les articles réellement traitables des autres (doublons et articles périmés).""" + keep, dropped, seen = [], [], set() + for article in articles: + title_key = normalize(article.get("title", ""))[:120] + if title_key and title_key in seen: + dropped.append((article, "titre déjà vu dans ce passage")) + continue + seen.add(title_key) + if is_stale(article): + dropped.append((article, f"article de plus de {MAX_AGE_DAYS} jours")) + continue + ok, reason = relevant(article, article.get("topic")) + (keep if ok else dropped).append(article if ok else (article, reason)) + return keep, dropped + + def article_hash(url): return hashlib.sha256(str(url).strip().encode("utf-8", "replace")).hexdigest()[:32] @@ -216,31 +344,62 @@ def analyse(article, topic, models=None): 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.""" + """Contrôle les actualités, préfiltre, puis n'interroge le modèle que sur du pertinent. + + Les articles écartés sont marqués comme tels : ils ne reviennent jamais dans la file et ne + créent donc aucun retard silencieux. + """ articles, errors = gather(topic_queries) fresh = storage.save_articles(articles, "geo") + candidates = [article for article in fresh if article.get("topic")] + keep, dropped = prefilter(candidates) + if dropped: + storage.mark_skipped([article["hash"] for article, _reason in dropped], "préfiltrage automatique") limit = limit or MAX_ARTICLES_PER_RUN - todo = [article for article in fresh if article.get("topic")][:limit] - events, analysed = 0, [] + todo = keep[:limit] + events, analysed, durations = 0, [], [] for article in todo: + started = time.monotonic() try: - found, _model = analyse(article, article["topic"], models=models) + found, model = analyse(article, article["topic"], models=models) except Exception as exc: + elapsed = time.monotonic() - started + duration = round(elapsed, 1) + durations.append(duration) + model = (models or llm.model_order())[0] + storage.record_llm_run( + article["hash"], article["topic"], model, duration, ok=False, detail=f"{type(exc).__name__}" + ) errors.append(f"ollama {article['hash'][:6]}: {type(exc).__name__}") continue + duration = round(time.monotonic() - started, 1) + durations.append(duration) + storage.record_llm_run(article["hash"], article["topic"], model, duration, ok=True) 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 [""]) + queue = storage.llm_queue() + detail = ( + "; ".join(errors[:3]) + if errors + else ( + f"{len(analysed)} analysé(s) en {sum(durations):.0f} s · " + f"{queue['pending']} en attente · modèle {', '.join(llm.model_order())}" + ) + ) return dict( status="ok" if articles else "error", articles=len(articles), new=len(todo), analysed=len(analysed), events=events, + skipped=len(dropped), + durations=durations, errors=errors[:6], + queue=queue, last_observation_at=newest or None, - detail="; ".join(errors[:3]) if errors else f"{len(analysed)} article(s) analysé(s)", + detail=detail, ) diff --git a/promotions.py b/promotions.py index 4b186ab..06b0340 100644 --- a/promotions.py +++ b/promotions.py @@ -9,6 +9,7 @@ est faite séparément, par le moteur de décision. from __future__ import annotations import os +import time import llm import news @@ -137,6 +138,54 @@ def analyse(article, models=None): MAX_ARTICLES_PER_RUN = int(os.environ.get("FUEL_PROMO_MAX_PER_RUN", "3")) +def relevant(article): + """Préfiltrage déterministe des annonces : enseigne connue **et** vocabulaire carburant.""" + text = news.normalize(article.get("title", "") + " " + (article.get("summary") or "")) + brand_hit = any(news.normalize(brand) in text for brand in BRANDS) + fuel_hit = any( + term in text + for term in ( + "carburant", + "essence", + "gazole", + "diesel", + "sp95", + "sp98", + "e10", + "e85", + "gpl", + "prix coutant", + "prix plafonne", + "remise", + "litre", + "plein", + "station", + "pompe", + ) + ) and any(term in text for term in ("prix", "remise", "litre", "operation", "promotion", "offre")) + if not fuel_hit: + return False, "pas de vocabulaire carburant" + if not brand_hit and "station" not in text and "pompe" not in text: + return False, "aucune enseigne identifiable" + return True, "" + + +def prefilter(articles): + keep, dropped, seen = [], [], set() + for article in articles: + title_key = news.normalize(article.get("title", ""))[:120] + if title_key and title_key in seen: + dropped.append((article, "titre déjà vu dans ce passage")) + continue + seen.add(title_key) + if news.is_stale(article): + dropped.append((article, f"article de plus de {news.MAX_AGE_DAYS} jours")) + continue + ok, reason = relevant(article) + (keep if ok else dropped).append(article if ok else (article, reason)) + return keep, dropped + + def collect(models=None, force=False, limit=None): """Recherche les opérations, n'analyse que les nouveaux articles, enregistre les annonces. @@ -145,28 +194,60 @@ def collect(models=None, force=False, limit=None): """ 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, [] + candidates = [article for article in fresh if article.get("topic")] + keep, dropped = prefilter(candidates) + if dropped: + storage.mark_skipped( + [article["hash"] for article, _reason in dropped], "préfiltrage automatique (promotions)" + ) + todo = keep[: limit or MAX_ARTICLES_PER_RUN] + saved, analysed, durations = 0, [], [] for article in todo: + started = time.monotonic() try: - found, _model = analyse(article, models=models) + found, model = analyse(article, models=models) except Exception as exc: + duration = round(time.monotonic() - started, 1) + durations.append(duration) + storage.record_llm_run( + article["hash"], + article.get("topic", ""), + llm.model_order()[0], + duration, + ok=False, + detail=type(exc).__name__, + ) errors.append(f"ollama {article['hash'][:6]}: {type(exc).__name__}") continue + duration = round(time.monotonic() - started, 1) + durations.append(duration) + storage.record_llm_run(article["hash"], article.get("topic", ""), model, duration, ok=True) 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 [""]) + queue = storage.llm_queue() + detail = ( + "; ".join(errors[:3]) + if errors + else ( + f"{saved} opération(s) · {len(analysed)} analysé(s) en {sum(durations):.0f} s · " + f"{queue['pending']} en attente" + ) + ) return dict( status="ok" if articles else "error", articles=len(articles), new=len(todo), analysed=len(analysed), promotions=saved, + skipped=len(dropped), + durations=durations, errors=errors[:6], + queue=queue, last_observation_at=newest or None, - detail="; ".join(errors[:3]) if errors else f"{saved} opération(s) enregistrée(s)", + detail=detail, ) diff --git a/routing.py b/routing.py new file mode 100644 index 0000000..62ec50a --- /dev/null +++ b/routing.py @@ -0,0 +1,212 @@ +"""Distances routières réelles : OSRM (par défaut, sans clé) ou Google Routes API (clé requise). + +Toujours une origine vers plusieurs destinations, avec distance **et** durée. En l'absence de +fournisseur joignable, rien n'est inventé : la réponse porte explicitement ``provider="none"`` +et l'application le signale au lieu de présenter une distance à vol d'oiseau comme une route. +""" + +from __future__ import annotations + +import json +import math +import os +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime, timezone + +MAX_TARGETS = int(os.environ.get("FUEL_ROUTING_MAX_TARGETS", "60")) +TIMEOUT = int(os.environ.get("FUEL_ROUTING_TIMEOUT", "20")) +OSRM_URL = os.environ.get("FUEL_OSRM_URL", "https://router.project-osrm.org").rstrip("/") +GOOGLE_KEY = ( + os.environ.get("FUEL_GOOGLE_MAPS_API_KEY") or os.environ.get("GOOGLE_MAPS_API_KEY") or "" +).strip() +USER_AGENT = os.environ.get("FUEL_HTTP_USER_AGENT", "CortexFuelAdvisor/0.5 (interne)") + + +def _get(url, timeout=TIMEOUT, data=None, headers=None): + request = urllib.request.Request( + url, data=data, headers=dict({"User-Agent": USER_AGENT}, **(headers or {})) + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.read() + + +def provider_osrm(origin, targets): + """Table OSRM : une origine, N destinations, distances et durées réelles.""" + coords = ";".join(f"{lon:.5f},{lat:.5f}" for lat, lon in [origin, *[t[1:] for t in targets]]) + url = f"{OSRM_URL}/table/v1/driving/{coords}?sources=0&annotations=distance,duration" + payload = json.loads(_get(url)) + if payload.get("code") != "Ok": + raise ValueError(f"OSRM a répondu {payload.get('code')}") + distances = (payload.get("distances") or [[]])[0] + durations = (payload.get("durations") or [[]])[0] + out = {} + for index, (station_id, _lat, _lon) in enumerate(targets, start=1): + meters = distances[index] if index < len(distances) else None + seconds = durations[index] if index < len(durations) else None + if meters is None or (isinstance(meters, float) and not math.isfinite(meters)): + continue + out[station_id] = dict( + distance_m=float(meters), duration_s=float(seconds) if seconds is not None else None + ) + return out + + +def provider_google(origin, targets): + """Google Routes API : computeRouteMatrix, une origine vers N destinations.""" + if not GOOGLE_KEY: + raise ValueError("clé Google absente (FUEL_GOOGLE_MAPS_API_KEY)") + body = json.dumps( + { + "origins": [ + {"waypoint": {"location": {"latLng": {"latitude": origin[0], "longitude": origin[1]}}}} + ], + "destinations": [ + {"waypoint": {"location": {"latLng": {"latitude": lat, "longitude": lon}}}} + for _id, lat, lon in targets + ], + "travelMode": "DRIVE", + "routingPreference": "TRAFFIC_AWARE", + } + ).encode() + raw = _get( + "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix", + data=body, + headers={ + "Content-Type": "application/json", + "X-Goog-Api-Key": GOOGLE_KEY, + "X-Goog-FieldMask": "originIndex,destinationIndex,status,condition,distanceMeters,duration", + }, + ) + out = {} + for row in json.loads(raw): + index = row.get("destinationIndex") + if index is None or index >= len(targets): + continue + if row.get("condition") and row["condition"] != "ROUTE_EXISTS": + continue + meters = row.get("distanceMeters") + if meters is None: + continue + seconds = str(row.get("duration") or "").rstrip("s") + out[targets[index][0]] = dict( + distance_m=float(meters), + duration_s=float(seconds) if seconds.replace(".", "", 1).isdigit() else None, + ) + return out + + +PROVIDERS = {"osrm": provider_osrm, "google": provider_google} + + +def provider_order(): + """Ordre configurable ; Google n'est tenté que si une clé existe réellement.""" + configured = [ + name.strip() + for name in os.environ.get("FUEL_ROUTING_PROVIDERS", "osrm,google").split(",") + if name.strip() + ] + usable = [] + for name in configured: + if name not in PROVIDERS: + continue + if name == "google" and not GOOGLE_KEY: + continue + usable.append(name) + return usable + + +def _route_key(origin, target): + return "|".join(f"{round(float(value), 4):.4f}" for value in (*origin, *target)) + + +def routes(origin, targets, cache_days=None): + """Distances routières pour des stations candidates, avec cache et chaîne de fournisseurs. + + ``origin`` : (lat, lon) ; ``targets`` : liste de (identifiant, lat, lon). + Retourne (routes, info) où ``info`` décrit le fournisseur réellement utilisé et les échecs. + """ + import storage + + targets = [(str(station_id), float(lat), float(lon)) for station_id, lat, lon in targets][:MAX_TARGETS] + cache_days = cache_days or int(os.environ.get("FUEL_ROUTE_CACHE_DAYS", "90")) + computed = {} + if not targets: + return computed, dict(provider="none", computed=0, from_cache=0, failures=[], note="") + + keys = {_route_key(origin, (lat, lon)): station_id for station_id, lat, lon in targets} + cached = storage.route_lookup(list(keys), max_age_days=cache_days) + for key, row in cached.items(): + station_id = keys.get(key) + if station_id: + computed[station_id] = dict( + distance_km=round(row["distance_m"] / 1000, 1), + duration_min=round(row["duration_s"] / 60, 1) if row["duration_s"] else None, + provider=row["provider"], + computed_at=row["computed_at"], + cached=True, + ) + + missing = [(station_id, lat, lon) for station_id, lat, lon in targets if station_id not in computed] + failures, used, fresh_rows = [], [], [] + if missing: + for name in provider_order(): + try: + found = PROVIDERS[name](origin, missing) + except Exception as exc: + failures.append(f"{name}: {type(exc).__name__}") + continue + if not found: + failures.append(f"{name}: aucune route renvoyée") + continue + used.append(name) + for station_id, data in found.items(): + computed[station_id] = dict( + distance_km=round(data["distance_m"] / 1000, 1), + duration_min=round(data["duration_s"] / 60, 1) + if data.get("duration_s") is not None + else None, + provider=name, + computed_at=datetime.now(timezone.utc).isoformat(), + cached=False, + ) + targets_by_id = {station_id: (lat, lon) for station_id, lat, lon in targets} + for station_id in found: + lat, lon = targets_by_id[station_id] + fresh_rows.append( + dict( + key=_route_key(origin, (lat, lon)), + origin_lat=origin[0], + origin_lon=origin[1], + target_lat=lat, + target_lon=lon, + distance_m=found[station_id]["distance_m"], + duration_s=found[station_id].get("duration_s"), + provider=name, + ) + ) + break + if fresh_rows: + storage.route_save(fresh_rows) + provider = used[0] if used else ("cache" if computed else "none") + missing_count = len(targets) - len(computed) + note = "" + if provider == "none": + note = ( + "Aucun service de routage joignable : les distances affichées restent à vol " + "d’oiseau et le rayon est appliqué à cette distance." + ) + elif missing_count: + note = ( + f"{missing_count} station(s) sans itinéraire routier calculable : elles ne sont pas " + "comptées avec une distance estimée." + ) + return computed, dict( + provider=provider, + computed=len(fresh_rows), + from_cache=len(cached), + failures=failures[:4], + stale_days=None if not computed else None, + note=note, + ) diff --git a/storage.py b/storage.py index 861a56a..106605f 100644 --- a/storage.py +++ b/storage.py @@ -318,6 +318,126 @@ def price_events(station_id=None, days=30): return [dict(row) for row in rows] +def route_key(origin, target, precision=4): + """Clé de cache : positions arrondies (la route ne change pas au mètre près).""" + parts = [round(float(value), precision) for value in (*origin, *target)] + return "|".join(f"{part:.{precision}f}" for part in parts) + + +def route_lookup(keys, max_age_days=90, now=None): + """Routes déjà calculées et encore valables (les routes changent lentement).""" + keys = list(keys) + if not keys: + return {} + now = now or datetime.now(timezone.utc) + floor = (now - timedelta(days=max_age_days)).isoformat() + out = {} + with connect() as db: + for chunk_start in range(0, len(keys), 400): + chunk = keys[chunk_start : chunk_start + 400] + placeholders = ",".join("?" * len(chunk)) + for row in db.execute( + f"SELECT * FROM route_cache WHERE key IN ({placeholders}) AND computed_at>=?", (*chunk, floor) + ): + out[row["key"]] = dict(row) + return out + + +def route_save(rows, now=None): + """Enregistre les distances routières calculées (base du futur coût de détour).""" + now = now or datetime.now(timezone.utc) + values = [ + ( + row["key"], + row["origin_lat"], + row["origin_lon"], + row["target_lat"], + row["target_lon"], + row["distance_m"], + row.get("duration_s"), + row["provider"], + now.isoformat(), + ) + for row in rows + if row.get("distance_m") and math.isfinite(row["distance_m"]) + ] + if not values: + return 0 + with connect() as db: + db.executemany( + """INSERT INTO route_cache VALUES(?,?,?,?,?,?,?,?,?) + ON CONFLICT(key) DO UPDATE SET distance_m=excluded.distance_m, + duration_s=excluded.duration_s,provider=excluded.provider,computed_at=excluded.computed_at""", + values, + ) + return len(values) + + +def record_llm_run(url_hash, topic, model, duration_s, ok=True, detail="", now=None): + stamp = (now or datetime.now(timezone.utc)).isoformat() + with connect() as db: + db.execute( + "REPLACE INTO llm_runs(url_hash,topic,model,duration_s,ok,detail,at) VALUES(?,?,?,?,?,?,?)", + ( + str(url_hash), + str(topic), + str(model), + float(duration_s), + 1 if ok else 0, + str(detail)[:200], + stamp, + ), + ) + + +def llm_queue(now=None): + """État réel de la file d'analyse : retard, débit et durée, jamais masqué.""" + now = now or datetime.now(timezone.utc) + day_ago = (now - timedelta(days=1)).isoformat() + with connect() as db: + pending = db.execute( + "SELECT count(*) n, min(fetched_at) oldest FROM news_articles " + "WHERE analysed_at IS NULL AND skip_reason IS NULL" + ).fetchone() + skipped = db.execute("SELECT count(*) n FROM news_articles WHERE skip_reason IS NOT NULL").fetchone() + total = db.execute("SELECT count(*) n FROM news_articles").fetchone() + analysed = db.execute( + "SELECT count(*) n FROM news_articles WHERE analysed_at>=?", (day_ago,) + ).fetchone() + durations = db.execute( + "SELECT count(*) n, avg(duration_s) avg_s, max(duration_s) max_s, sum(ok = 0) fails " + "FROM llm_runs WHERE at>=?", + (day_ago,), + ).fetchone() + by_model = [ + dict(row) + for row in db.execute( + "SELECT model, count(*) n, avg(duration_s) avg_s, sum(ok = 0) fails FROM llm_runs " + "WHERE at>=? GROUP BY model ORDER BY n DESC", + (day_ago,), + ) + ] + oldest = pending["oldest"] + age_hours = None + if oldest: + try: + age_hours = round((now - datetime.fromisoformat(oldest)).total_seconds() / 3600, 1) + except ValueError: + age_hours = None + return dict( + pending=pending["n"], + oldest_pending_at=oldest, + oldest_pending_age_hours=age_hours, + skipped=skipped["n"], + total=total["n"], + analysed_24h=analysed["n"], + analysed_24h_avg_seconds=round(durations["avg_s"], 1) if durations["avg_s"] else None, + analysed_24h_max_seconds=round(durations["max_s"], 1) if durations["max_s"] else None, + analysed_24h_failures=durations["fails"] or 0, + by_model=by_model, + ) + + def job_get(name): with connect() as db: row = db.execute("SELECT * FROM jobs WHERE name=?", (name,)).fetchone() @@ -382,7 +502,8 @@ def save_articles(articles, topic, now=None): 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)", + "REPLACE INTO news_articles(url_hash,url,title,source,published_at,observed_at," + "fetched_at,topic,analysed_at,skip_reason) VALUES(?,?,?,?,?,?,?,?,NULL,NULL)", ( digest, article["url"], @@ -400,6 +521,32 @@ def save_articles(articles, topic, now=None): return fresh +def mark_skipped(hashes, reason, now=None): + """Article écarté par le préfiltrage : conservé, daté, et jamais réanalysé.""" + 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=?, skip_reason=? WHERE url_hash=?", + (stamp, str(reason)[:120], digest), + ) + return len(hashes) + + +def pending_articles(limit=50, topic=None): + """Articles en attente d'analyse, du plus ancien au plus récent.""" + query = "SELECT * FROM news_articles WHERE analysed_at IS NULL AND skip_reason IS NULL" + args = [] + if topic: + query += " AND topic=?" + args.append(topic) + with connect() as db: + rows = db.execute(query + " ORDER BY fetched_at LIMIT ?", (*args, limit)).fetchall() + return [dict(row) for row in rows] + + def mark_analysed(hashes, now=None): stamp = (now or datetime.now(timezone.utc)).isoformat() if not hashes: @@ -695,6 +842,14 @@ def connect(): 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 route_cache ( + key TEXT PRIMARY KEY, origin_lat REAL NOT NULL, origin_lon REAL NOT NULL, + target_lat REAL NOT NULL, target_lon REAL NOT NULL, distance_m REAL NOT NULL, + duration_s REAL, provider TEXT NOT NULL, computed_at TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS llm_runs ( + id INTEGER PRIMARY KEY, url_hash TEXT NOT NULL, topic TEXT NOT NULL DEFAULT '', + model TEXT NOT NULL, duration_s REAL NOT NULL, ok INTEGER NOT NULL DEFAULT 1, + detail TEXT NOT NULL DEFAULT '', at TEXT NOT NULL); 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 '', @@ -707,6 +862,7 @@ def connect(): """) _ensure_columns(db, "upstream_series", {"observed_at": "TEXT", "published_at": "TEXT"}) _ensure_columns(db, "observations", {"published_at": "TEXT", "fetched_at": "TEXT"}) + _ensure_columns(db, "news_articles", {"skip_reason": "TEXT"}) yield db finally: db.close() diff --git a/style.css b/style.css index f083128..9938043 100644 --- a/style.css +++ b/style.css @@ -1 +1 @@ -:root{color-scheme:dark;--bg:#0b1220;--panel:#142035;--line:#29374b;--text:#edf3fa;--muted:#a2b0c4;--accent:#68dfc3;--warn:#f9cb72;--bad:#ff9393}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top left,#193749,transparent 65%),var(--bg);font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;color:var(--text);min-height:100vh}main{max-width:1240px;margin:auto;padding:36px 24px}header{display:flex;justify-content:space-between;align-items:center;gap:24px;margin-bottom:30px}.eyebrow{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--accent);font-weight:750}h1{font-size:clamp(32px,4vw,52px);line-height:1.08;letter-spacing:-.045em;margin:12px 0}h1 span{color:var(--accent)}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 16px}h3{font-size:16px;margin:22px 0 10px}p{margin:10px 0}.header-actions,.inline,.section-title,.dialog-head,.item-actions{display:flex;align-items:center;gap:10px}.layout{display:grid;grid-template-columns:355px minmax(0,1fr);gap:20px}aside,#result{display:grid;gap:18px;align-content:start}.card{background:linear-gradient(135deg,#17263b,#101c2d);border:1px solid var(--line);border-radius:20px;padding:24px;box-shadow:0 12px 30px #0002}.compact{padding:20px}.section-title,.dialog-head{justify-content:space-between}.section-title h2{margin:0;font-size:17px}label{display:block;font-size:13px;font-weight:650;color:#c6d4e7;margin:16px 0 7px}input,select{display:block;width:100%;background:#0b1627;color:var(--text);border:1px solid #36465c;border-radius:10px;padding:11px 12px;font:inherit;min-height:44px}label input,label select{margin-top:7px}input:focus,select:focus,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{font:inherit;font-size:13px;font-weight:700;border:1px solid transparent;border-radius:10px;padding:11px 14px;cursor:pointer;min-height:42px;white-space:normal}.primary{background:var(--accent);color:#09211e}.secondary{background:#203048;color:var(--text);border-color:#34455b}button:hover{filter:brightness(1.12)}button:disabled{opacity:.55;cursor:wait}select:disabled{opacity:.75}.wide{width:100%;margin-top:20px}.small{padding:6px 10px;min-height:34px;font-size:12px}.hint,.muted{color:var(--muted);font-size:13px}.hint:empty,.form-error:empty{display:none}.inline>input,.inline>div{min-width:0;flex:1}.location-actions{margin-top:12px}.location-label{font-size:12px;color:var(--accent);padding-top:30px;overflow-wrap:anywhere}.empty{min-height:320px;padding-top:36px}.empty h2{font-size:26px;margin:16px 0}.empty p{max-width:520px;color:var(--muted)}.tags{display:flex;flex-wrap:wrap;gap:8px;margin-top:20px}.tags span,.badge{font-size:11px;background:#23374a;color:#cee5e5;padding:5px 9px;border-radius:7px}.badge{display:inline-block;margin:0 6px 6px 0}.badge.brand{background:#1d4a44;color:#a7f3e3;font-weight:700}.station-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px;margin:14px 0}.station-card{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:12px}.station-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px}.station-head strong{font-size:14px;overflow-wrap:anywhere}.station-head span{font-size:17px;font-weight:750;color:var(--accent);white-space:nowrap}.station-head small{font-size:10px;color:var(--muted)}.station-card p{margin:4px 0}.job-head{display:flex;justify-content:space-between;align-items:baseline;gap:10px}.mini{width:100%;height:52px;display:block;margin:8px 0}.mini polyline{stroke:var(--accent);stroke-width:2;fill:none;vector-effect:non-scaling-stroke}.mini circle{fill:var(--accent)}.verdict{font-size:clamp(24px,3vw,34px);line-height:1.2;margin:12px 0 20px}.tone-refuel,.tone-topup{color:var(--warn)}.tone-wait,.tone-none{color:var(--accent)}.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:18px 0}.metric{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:14px}.metric strong{display:block;font-size:22px;line-height:1.4}.metric span{font-size:11px;color:var(--muted)}.reasons{padding-left:19px;color:#c1cee0;font-size:13px}.reasons li{margin:8px 0}.notice{padding:12px;border:1px solid #78603c;background:#382d1e;color:#f3d9ac;border-radius:10px;font-size:13px}.station{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;border-top:1px solid var(--line);padding:15px 0}.station:first-child{border-top:0}.station strong{font-size:14px;overflow-wrap:anywhere}.station .price{font-size:23px;font-weight:750;color:var(--accent);white-space:nowrap}.station .price small{font-size:11px}.station p{margin:2px 0}.buckets{display:flex;gap:6px;flex-wrap:wrap;max-height:110px;overflow:auto;margin:12px 0}.bucket{font-size:11px;padding:4px 7px;background:#203048;border-radius:6px}.chart{width:100%;height:170px;display:block;margin-top:16px}.chart polyline{stroke:var(--accent);stroke-width:2.5;fill:none;vector-effect:non-scaling-stroke}.chart circle{fill:var(--accent)}.chart text{fill:var(--muted);font-size:10px}.chart line{stroke:var(--line)}.error,.form-error{color:var(--bad);font-size:13px}.loading{color:var(--muted);padding:32px}.two{display:grid;grid-template-columns:1fr 1fr;gap:14px}dialog{border:1px solid #35465b;border-radius:20px;background:var(--panel);color:var(--text);width:min(560px,calc(100% - 24px));max-height:90vh;padding:24px;box-shadow:0 30px 100px #0009}dialog::backdrop{background:#030a16b8}dialog h2{margin:0}.close{font-size:24px;padding:0 12px}form h3{border-top:1px solid var(--line);padding-top:18px}form button[type=submit]{margin-top:20px}.item{padding:14px 0;border-bottom:1px solid var(--line)}.item-actions{margin-top:8px}.items{margin-bottom:16px}footer{font-size:11px;color:#8a9bb1;margin-top:30px;max-width:950px}details{margin-top:16px}summary{cursor:pointer;color:#cbd8e8;font-size:13px}[hidden]{display:none!important}@media(max-width:850px){main{padding:22px 16px}.layout{grid-template-columns:1fr}header{align-items:flex-start;flex-direction:column;gap:14px}.header-actions{width:100%}.header-actions button{flex:1}.card{padding:20px}.empty{min-height:240px}.metrics{gap:6px}.metric{padding:11px}.metric strong{font-size:19px}.two{gap:10px}.station .price{font-size:20px}} +:root{color-scheme:dark;--bg:#0b1220;--panel:#142035;--line:#29374b;--text:#edf3fa;--muted:#a2b0c4;--accent:#68dfc3;--warn:#f9cb72;--bad:#ff9393}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top left,#193749,transparent 65%),var(--bg);font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;color:var(--text);min-height:100vh}main{max-width:1240px;margin:auto;padding:36px 24px}header{display:flex;justify-content:space-between;align-items:center;gap:24px;margin-bottom:30px}.eyebrow{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--accent);font-weight:750}h1{font-size:clamp(32px,4vw,52px);line-height:1.08;letter-spacing:-.045em;margin:12px 0}h1 span{color:var(--accent)}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 16px}h3{font-size:16px;margin:22px 0 10px}p{margin:10px 0}.header-actions,.inline,.section-title,.dialog-head,.item-actions{display:flex;align-items:center;gap:10px}.layout{display:grid;grid-template-columns:355px minmax(0,1fr);gap:20px}aside,#result{display:grid;gap:18px;align-content:start}.card{background:linear-gradient(135deg,#17263b,#101c2d);border:1px solid var(--line);border-radius:20px;padding:24px;box-shadow:0 12px 30px #0002}.compact{padding:20px}.section-title,.dialog-head{justify-content:space-between}.section-title h2{margin:0;font-size:17px}label{display:block;font-size:13px;font-weight:650;color:#c6d4e7;margin:16px 0 7px}input,select{display:block;width:100%;background:#0b1627;color:var(--text);border:1px solid #36465c;border-radius:10px;padding:11px 12px;font:inherit;min-height:44px}label input,label select{margin-top:7px}input:focus,select:focus,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{font:inherit;font-size:13px;font-weight:700;border:1px solid transparent;border-radius:10px;padding:11px 14px;cursor:pointer;min-height:42px;white-space:normal}.primary{background:var(--accent);color:#09211e}.secondary{background:#203048;color:var(--text);border-color:#34455b}button:hover{filter:brightness(1.12)}button:disabled{opacity:.55;cursor:wait}select:disabled{opacity:.75}.wide{width:100%;margin-top:20px}.small{padding:6px 10px;min-height:34px;font-size:12px}.hint,.muted{color:var(--muted);font-size:13px}.hint:empty,.form-error:empty{display:none}.inline>input,.inline>div{min-width:0;flex:1}.location-actions{margin-top:12px}.location-label{font-size:12px;color:var(--accent);padding-top:30px;overflow-wrap:anywhere}.empty{min-height:320px;padding-top:36px}.empty h2{font-size:26px;margin:16px 0}.empty p{max-width:520px;color:var(--muted)}.tags{display:flex;flex-wrap:wrap;gap:8px;margin-top:20px}.tags span,.badge{font-size:11px;background:#23374a;color:#cee5e5;padding:5px 9px;border-radius:7px}.badge{display:inline-block;margin:0 6px 6px 0}.badge.brand{background:#1d4a44;color:#a7f3e3;font-weight:700}.station-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px;margin:14px 0}.station-card{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:12px}.station-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px}.station-head strong{font-size:14px;overflow-wrap:anywhere}.station-head span{font-size:17px;font-weight:750;color:var(--accent);white-space:nowrap}.station-head small{font-size:10px;color:var(--muted)}.station-card p{margin:4px 0}.job-head{display:flex;justify-content:space-between;align-items:baseline;gap:10px}.nav-actions{display:flex;gap:8px;margin-top:10px}.nav-btn{font-size:12px;font-weight:700;color:#09211e;background:var(--accent);border-radius:8px;padding:7px 11px;text-decoration:none;white-space:nowrap}.nav-btn+.nav-btn{background:#2f4a68;color:var(--text)}.pressure{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:14px 16px;border-radius:12px;background:#0d192a;border:1px solid #25364b;margin-bottom:14px}.pressure strong{font-size:17px}.pressure-up{border-color:#8a6a3c;background:#2c2317}.pressure-down{border-color:#2f6a5c;background:#12261f}.factors{display:grid;gap:10px}.factor{display:grid;grid-template-columns:34px minmax(0,1fr);gap:12px;align-items:start;border-top:1px solid var(--line);padding-top:10px}.factor:first-child{border-top:0}.factor-arrow{font-size:20px;text-align:center}.arrow-up{color:var(--warn)}.arrow-down{color:var(--accent)}.arrow-flat{color:var(--muted)}.arrow-unknown{color:#8894a6}.factor p{margin:2px 0}.mini{width:100%;height:52px;display:block;margin:8px 0}.mini polyline{stroke:var(--accent);stroke-width:2;fill:none;vector-effect:non-scaling-stroke}.mini circle{fill:var(--accent)}.verdict{font-size:clamp(24px,3vw,34px);line-height:1.2;margin:12px 0 20px}.tone-refuel,.tone-topup{color:var(--warn)}.tone-wait,.tone-none{color:var(--accent)}.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:18px 0}.metric{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:14px}.metric strong{display:block;font-size:22px;line-height:1.4}.metric span{font-size:11px;color:var(--muted)}.reasons{padding-left:19px;color:#c1cee0;font-size:13px}.reasons li{margin:8px 0}.notice{padding:12px;border:1px solid #78603c;background:#382d1e;color:#f3d9ac;border-radius:10px;font-size:13px}.station{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;border-top:1px solid var(--line);padding:15px 0}.station:first-child{border-top:0}.station strong{font-size:14px;overflow-wrap:anywhere}.station .price{font-size:23px;font-weight:750;color:var(--accent);white-space:nowrap}.station .price small{font-size:11px}.station p{margin:2px 0}.buckets{display:flex;gap:6px;flex-wrap:wrap;max-height:110px;overflow:auto;margin:12px 0}.bucket{font-size:11px;padding:4px 7px;background:#203048;border-radius:6px}.chart{width:100%;height:170px;display:block;margin-top:16px}.chart polyline{stroke:var(--accent);stroke-width:2.5;fill:none;vector-effect:non-scaling-stroke}.chart circle{fill:var(--accent)}.chart text{fill:var(--muted);font-size:10px}.chart line{stroke:var(--line)}.error,.form-error{color:var(--bad);font-size:13px}.loading{color:var(--muted);padding:32px}.two{display:grid;grid-template-columns:1fr 1fr;gap:14px}dialog{border:1px solid #35465b;border-radius:20px;background:var(--panel);color:var(--text);width:min(560px,calc(100% - 24px));max-height:90vh;padding:24px;box-shadow:0 30px 100px #0009}dialog::backdrop{background:#030a16b8}dialog h2{margin:0}.close{font-size:24px;padding:0 12px}form h3{border-top:1px solid var(--line);padding-top:18px}form button[type=submit]{margin-top:20px}.item{padding:14px 0;border-bottom:1px solid var(--line)}.item-actions{margin-top:8px}.items{margin-bottom:16px}footer{font-size:11px;color:#8a9bb1;margin-top:30px;max-width:950px}details{margin-top:16px}summary{cursor:pointer;color:#cbd8e8;font-size:13px}[hidden]{display:none!important}@media(max-width:850px){main{padding:22px 16px}.layout{grid-template-columns:1fr}header{align-items:flex-start;flex-direction:column;gap:14px}.header-actions{width:100%}.header-actions button{flex:1}.card{padding:20px}.empty{min-height:240px}.metrics{gap:6px}.metric{padding:11px}.metric strong{font-size:19px}.two{gap:10px}.station .price{font-size:20px}} diff --git a/synthesis.py b/synthesis.py new file mode 100644 index 0000000..e590b92 --- /dev/null +++ b/synthesis.py @@ -0,0 +1,480 @@ +"""Synthèse lisible des signaux amont : pression, facteurs en langage courant, « En clair ». + +Tout est calculé depuis les séries structurées déjà historisées. Aucune valeur n'est inventée : +un facteur sans donnée fraîche ressort en « information insuffisante ». Le texte peut être +reformulé par Ollama ailleurs, mais jamais le sens d'un indicateur. +""" + +from __future__ import annotations + +from datetime import date, datetime, timedelta, timezone + +import storage + +UP, DOWN, FLAT, UNKNOWN = "up", "down", "flat", "unknown" +ARROWS = {UP: "↑", DOWN: "↓", FLAT: "→", UNKNOWN: "?"} +DIRECTION_WORDS = { + UP: "pousse les prix à la hausse", + DOWN: "pousse les prix à la baisse", + FLAT: "peu d’effet", + UNKNOWN: "information insuffisante", +} +DIRECTION_LABELS = {UP: "hausse", DOWN: "baisse", FLAT: "peu d’effet", UNKNOWN: "incertaine"} +PRESSURE_LABELS = {"up": "HAUSSE", "down": "BAISSE", "flat": "NEUTRE", "unknown": "INCERTAINE"} + +# Poids explicites : ce sont eux qui décident, pas un modèle. Ils seront ajustés plus tard +# uniquement si un décalage vérifié vers la pompe le justifie. +FACTOR_WEIGHTS = { + "brut": 0.30, + "change": 0.15, + "raffinage": 0.15, + "produits": 0.20, + "logistique": 0.10, + "evenements": 0.10, +} +FRESH_DAYS = 10 +FUEL_LABELS = { + "Gazole": "gazole", + "SP95": "SP95", + "SP95-E10": "SP95-E10", + "SP98": "SP98", + "E85": "E85", + "GPLc": "GPLc", +} + + +def _decorate(factor): + """Ajoute flèche et libellés : la présentation ne dépend jamais de l'appelant.""" + factor = dict(factor) + direction = factor.get("direction", UNKNOWN) + factor["arrow"] = ARROWS[direction] + factor["direction_text"] = DIRECTION_WORDS[direction] + factor["direction_label"] = DIRECTION_LABELS[direction] + return factor + + +def _series(name, days): + return [row for row in storage.upstream_series(name, days=days) if row.get("value") is not None] + + +def _last(rows): + return rows[-1] if rows else None + + +def _reference(rows, days): + """Valeur de référence : la plus ancienne de la fenêtre, sinon la première disponible.""" + if not rows: + return None + limit = (date.today() - timedelta(days=days)).isoformat() + older = [row for row in rows if str(row["day"]) <= limit] + return older[-1] if older else rows[0] + + +def _freshness(rows, threshold_days=FRESH_DAYS): + last = _last(rows) + if not last: + return None + try: + age = (datetime.now(timezone.utc).date() - date.fromisoformat(str(last["day"]))).days + except ValueError: + return None + return dict(age_days=age, fresh=age <= threshold_days) + + +def _direction(change_pct, threshold): + if change_pct is None: + return UNKNOWN + if change_pct >= threshold: + return UP + if change_pct <= -threshold: + return DOWN + return FLAT + + +def _trend_factor(series_names, days, threshold, source=None): + """Facteur générique : variation d'une série sur une fenêtre, en pourcentage.""" + rows, used = [], None + for name in series_names: + rows = _series(name, days * 3) + if rows: + used = name + break + if len(rows) < 2: + return None + last, reference = _last(rows), _reference(rows, days) + if not reference or not reference.get("value"): + return None + change = (last["value"] - reference["value"]) / reference["value"] * 100 + fresh = _freshness(rows) or {} + return _decorate( + dict( + direction=_direction(change, threshold), + change_pct=round(change, 2), + unit="%", + observed_at=str(last["day"]), + value=last["value"], + reference=reference["value"], + reference_day=str(reference["day"]), + source=source or last.get("source") or used, + age_days=fresh.get("age_days"), + fresh=bool(fresh.get("fresh")), + series=used, + ) + ) + + +def factor_brut(days=7): + """Pétrole brut : le prix du baril, sur une semaine.""" + factor = _trend_factor( + ["brent_eur_daily", "brent_usd_daily", "dgec_brent_usd"], + days, + threshold=1.5, + source="Brent (cotation et DGEC)", + ) + if not factor: + return _decorate( + dict( + key="brut", + label="Pétrole brut", + direction=UNKNOWN, + weight=FACTOR_WEIGHTS["brut"], + explanation="Aucune cotation récente exploitable du baril.", + ) + ) + factor.update( + key="brut", + label="Pétrole brut", + weight=FACTOR_WEIGHTS["brut"], + explanation=( + f"Le baril a varié de {factor['change_pct']:+.1f} % sur la période observée " + f"({factor['reference_day']} → {factor['observed_at']}). Le brut est la matière première : " + "quand il monte, les prix à la pompe finissent souvent par suivre, avec du retard." + ), + ) + return factor + + +def factor_change(days=7): + """Euro/dollar : un euro faible renchérit un baril coté en dollars.""" + factor = _trend_factor(["usd_per_eur"], days, threshold=0.8, source="BCE (taux de référence)") + if not factor: + return _decorate( + dict( + key="change", + label="Euro / dollar", + direction=UNKNOWN, + weight=FACTOR_WEIGHTS["change"], + explanation="Taux de change indisponible : effet non évalué.", + ) + ) + factor.update( + key="change", + label="Euro / dollar", + weight=FACTOR_WEIGHTS["change"], + explanation=( + f"L'euro a évolué de {factor['change_pct']:+.1f} % face au dollar sur la période. " + "Le pétrole se paie en dollars : un euro plus faible renchérit mécaniquement le baril " + "pour nous, et inversement." + ), + ) + return factor + + +def factor_raffinage(days=35): + """Marge de raffinage : le coût de transformation du brut en carburant.""" + factor = _trend_factor( + ["dgec_margin_eur_per_tonne"], days, threshold=8, source="DGEC (marge brute de raffinage)" + ) + if not factor: + return _decorate( + dict( + key="raffinage", + label="Raffinage", + direction=UNKNOWN, + weight=FACTOR_WEIGHTS["raffinage"], + explanation="Marge de raffinage non disponible pour la période.", + ) + ) + factor.update( + key="raffinage", + label="Raffinage", + weight=FACTOR_WEIGHTS["raffinage"], + explanation=( + f"La marge brute de raffinage a varié de {factor['change_pct']:+.1f} % entre " + f"{factor['reference_day']} et {factor['observed_at']}. Quand la transformation coûte " + "plus cher, la pompe le ressent ; c’est un indicateur mensuel, donc lent." + ), + ) + return factor + + +def factor_produits(fuel="Gazole", days=28): + """Produits raffinés : prix hors taxes du carburant, en France et dans l'UE.""" + label = FUEL_LABELS.get(fuel, fuel) + diesel = "Gazole" in fuel + candidates = [f"fr_htt_{fuel}", "eu_fr_diesel_htt" if diesel else "eu_fr_euro95_htt"] + factor = _trend_factor( + candidates, days, threshold=2.0, source="DGEC et Commission européenne (hors taxes)" + ) + if not factor: + return _decorate( + dict( + key="produits", + label=f"Produits raffinés ({label})", + direction=UNKNOWN, + weight=FACTOR_WEIGHTS["produits"], + explanation="Prix hors taxes du produit non disponible.", + ) + ) + factor.update( + key="produits", + label=f"Produits raffinés ({label})", + weight=FACTOR_WEIGHTS["produits"], + explanation=( + f"Le prix hors taxes du {label} a varié de {factor['change_pct']:+.1f} % sur " + f"{factor['reference_day']} → {factor['observed_at']}. C’est la composante « produit » " + "du prix, avant taxes et distribution." + ), + ) + return factor + + +def factor_logistique(days=30): + """Détroits : quand les passages ralentissent, l'approvisionnement se tend.""" + per_chokepoint = { + name: entries for name, entries in storage.chokepoint_daily(days=days).items() if entries + } + if not per_chokepoint: + return _decorate( + dict( + key="logistique", + label="Ormuz et détroits", + direction=UNKNOWN, + weight=FACTOR_WEIGHTS["logistique"], + explanation="Aucune observation récente des détroits.", + ) + ) + changes, details, newest = [], [], None + for name, entries in per_chokepoint.items(): + entries.sort(key=lambda item: item["day"]) + values = [entry["transit_tankers"] for entry in entries if entry.get("transit_tankers")] + if len(values) < 3: + continue + reference = sorted(values)[len(values) // 2] + if not reference: + continue + changes.append((values[-1] - reference) / reference * 100) + details.append(f"{name} : {values[-1]} pétroliers contre {reference} habituellement") + newest = max(newest or "", entries[-1]["day"]) + if not changes: + return _decorate( + dict( + key="logistique", + label="Ormuz et détroits", + direction=UNKNOWN, + weight=FACTOR_WEIGHTS["logistique"], + explanation="Historique des détroits trop court pour comparer.", + ) + ) + average = sum(changes) / len(changes) + # Moins de pétroliers en circulation = approvisionnement plus tendu = pression haussière. + direction = _direction(-average, 10) + return _decorate( + dict( + key="logistique", + label="Ormuz et détroits", + direction=direction, + weight=FACTOR_WEIGHTS["logistique"], + change_pct=round(-average, 2), + observed_at=newest, + source="IMF PortWatch (base du moniteur IEA)", + age_days=None, + fresh=True, + evidence_text=" · ".join(details[:3]), + explanation=( + "Trafic de pétroliers dans les détroits surveillés : " + + ( + "en baisse, ce qui tend l’approvisionnement mondial" + if average < -10 + else "stable ou en hausse, sans tension détectée" + ) + + ". Un choc sur ces flux peut peser sur les prix même s’il ne concerne pas directement " + "la France." + ), + ) + ) + + +def factor_evenements(days=21): + """Événements géopolitiques extraits des actualités, pondérés par leur confiance.""" + events = storage.news_events(days=days) + if not events: + return _decorate( + dict( + key="evenements", + label="Géopolitique et logistique", + direction=UNKNOWN, + weight=FACTOR_WEIGHTS["evenements"], + explanation="Aucun événement pertinent retenu pour la période.", + ) + ) + score, weights, examples = 0.0, 0.0, [] + for event in events: + confidence = event.get("confidence") + confidence = 0.5 if confidence is None else max(0.0, min(1.0, float(confidence))) + if event["direction"] == "hausse": + score += confidence + elif event["direction"] == "baisse": + score -= confidence + weights += confidence + if len(examples) < 3 and event.get("zone"): + examples.append(f"{event['event_type']} ({event['zone']})") + if not weights: + direction = UNKNOWN + elif score / weights >= 0.25: + direction = UP + elif score / weights <= -0.25: + direction = DOWN + else: + direction = FLAT + tail = { + UP: ". Ensemble, ils pèsent plutôt à la hausse.", + DOWN: ". Ensemble, ils pèsent plutôt à la baisse.", + FLAT: ". Ensemble, leur effet reste limité ou contradictoire.", + UNKNOWN: ". Leur sens reste trop incertain pour trancher.", + }[direction] + return _decorate( + dict( + key="evenements", + label="Géopolitique et logistique", + direction=direction, + weight=FACTOR_WEIGHTS["evenements"], + confidence_used=round(weights, 2), + count=len(events), + observed_at=( + max((event.get("published_at") or event.get("fetched_at") or "") for event in events)[:10] + or None + ), + source="Articles de presse, extraction structurée", + fresh=True, + age_days=None, + evidence_text=" · ".join(examples), + explanation=f"{len(events)} événement(s) suivi(s) sur la période" + + (f" : {', '.join(examples)}" if examples else "") + + tail, + ) + ) + + +def pressure(factors): + """Pression d'ensemble : vote pondéré explicable, jamais une prévision.""" + known = [factor for factor in factors if factor["direction"] != UNKNOWN] + if not known: + return dict( + label=PRESSURE_LABELS["unknown"], + key="unknown", + score=None, + known=0, + total=len(factors), + confidence=None, + agreement=None, + fresh=None, + ) + weight_total = sum(factor["weight"] for factor in known) + score = sum( + factor["weight"] * (1 if factor["direction"] == UP else -1 if factor["direction"] == DOWN else 0) + for factor in known + ) + score /= weight_total + coverage = len(known) / len(factors) + agreement = abs(score) + fresh = sum(1 for factor in known if factor.get("fresh")) / len(known) + confidence = round(min(0.8, 0.35 * coverage + 0.35 * agreement + 0.30 * fresh), 2) + if score >= 0.2: + key = "up" + elif score <= -0.2: + key = "down" + elif len(known) >= 3: + key = "flat" + else: + key = "unknown" + return dict( + label=PRESSURE_LABELS[key], + key=key, + score=round(score, 3), + known=len(known), + total=len(factors), + confidence=confidence, + agreement=round(agreement, 2), + fresh=round(fresh, 2), + ) + + +def plain_language(verdict, factors): + """Paragraphe « En clair » : déterminé par les calculs, pas par un modèle.""" + driving_up = [factor["label"] for factor in factors if factor["direction"] == UP] + driving_down = [factor["label"] for factor in factors if factor["direction"] == DOWN] + top = sorted( + [factor for factor in factors if factor["direction"] != UNKNOWN], key=lambda factor: -factor["weight"] + )[:2] + top_text = " et ".join(factor["label"].lower() for factor in top) + first = { + "up": "En ce moment, les signaux que nous suivons pèsent plutôt vers des prix qui montent.", + "down": "En ce moment, les signaux que nous suivons pèsent plutôt vers des prix qui " + "baissent ou se stabilisent.", + "flat": "En ce moment, rien ne pousse franchement les prix dans un sens ou dans l’autre.", + "unknown": "En ce moment, nous n’avons pas assez de données fraîches pour dire dans quel " + "sens les prix amont poussent.", + }[verdict["key"]] + if driving_up and driving_down: + second = ( + f" Certains éléments poussent à la hausse ({', '.join(driving_up[:2])}) et " + f"d’autres à la baisse ({', '.join(driving_down[:2])}) : ils se compensent en partie." + ) + elif driving_up: + second = f" Ce qui pèse le plus : {', '.join(driving_up[:3])}." + elif driving_down: + second = f" Ce qui pèse le plus : {', '.join(driving_down[:3])}." + elif top_text: + second = f" Les facteurs les plus suivis ({top_text}) n’évoluent pas assez pour trancher." + else: + second = "" + return ( + first + second + " Concrètement, cela ne dit pas encore quel sera le prix à la pompe " + "demain : le délai de transmission entre le marché amont et les stations françaises " + "n’est pas encore mesuré sur assez de données. À utiliser comme contexte, jamais comme " + "une prévision validée." + ) + + +def build(fuel="Gazole"): + """Synthèse complète : pression, facteurs, phrase « En clair », avertissement explicite.""" + factors = [ + factor_brut(), + factor_change(), + factor_raffinage(), + factor_produits(fuel), + factor_logistique(), + factor_evenements(), + ] + verdict = pressure(factors) + return dict( + fuel=fuel, + pressure=verdict["label"], + pressure_key=verdict["key"], + confidence=verdict["confidence"], + score=verdict["score"], + known_factors=verdict["known"], + total_factors=verdict["total"], + agreement=verdict["agreement"], + freshness=verdict["fresh"], + factors=factors, + plain=plain_language(verdict, factors), + disclaimer=( + "Synthèse calculée à partir des données amont historisées. Ce n’est pas encore " + "une prévision validée du prix à la pompe : aucune transmission marché → pompe " + "n’a été vérifiée sur un historique suffisant." + ), + generated_at=datetime.now(timezone.utc).isoformat(), + weights=FACTOR_WEIGHTS, + ) diff --git a/tests/conftest.py b/tests/conftest.py index 8fe982d..1ccec50 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,6 +9,7 @@ import llm import market import news import promotions +import routing import storage @@ -19,6 +20,9 @@ def isolated_environment(tmp_path, monkeypatch): monkeypatch.setattr(module, "DB_PATH", tmp_path / f"{module.__name__}.sqlite3") monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: []) monkeypatch.setattr(market, "PROVIDERS", {}) + monkeypatch.setattr(routing, "PROVIDERS", {"osrm": lambda *a, **k: {}, "google": lambda *a, **k: {}}) + monkeypatch.delenv("FUEL_ROUTING_PROVIDERS", raising=False) + monkeypatch.delenv("FUEL_GOOGLE_MAPS_API_KEY", raising=False) monkeypatch.setattr(news, "gather", lambda *args, **kwargs: ([], [])) monkeypatch.setattr(promotions, "gather", lambda *args, **kwargs: ([], [])) monkeypatch.setattr( diff --git a/tests/test_routing.py b/tests/test_routing.py new file mode 100644 index 0000000..5b7edc3 --- /dev/null +++ b/tests/test_routing.py @@ -0,0 +1,180 @@ +"""Distances routières : fournisseurs, cache, application du rayon, liens de navigation.""" + +import json + +import pytest + +import app +import routing + + +def station_row(station_id, lat, lon, price=1.9, fuel="Gazole"): + return dict( + id=station_id, + name=f"Station {station_id}", + address="Rue", + city="Nantes", + lat=lat, + lon=lon, + prices={fuel: price}, + updates={fuel: "2026-09-12 08:00:00"}, + road="", + ) + + +def test_provider_order_skips_google_without_key(monkeypatch): + monkeypatch.delenv("FUEL_GOOGLE_MAPS_API_KEY", raising=False) + monkeypatch.setattr(routing, "GOOGLE_KEY", "") + assert routing.provider_order() == ["osrm"] + monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google,osrm") + assert routing.provider_order() == ["osrm"], "Google sans clé ne doit jamais être tenté" + monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test") + assert routing.provider_order() == ["google", "osrm"] + + +def test_provider_osrm_parses_table_and_drops_unreachable(monkeypatch): + payload = json.dumps( + {"code": "Ok", "distances": [[0, 3699.3, None]], "durations": [[0, 580.3, None]]} + ).encode() + monkeypatch.setattr(routing, "_get", lambda *args, **kwargs: payload) + found = routing.provider_osrm((48.85, 2.35), [("A", 48.86, 2.30), ("B", 48.90, 2.25)]) + assert found["A"]["distance_m"] == pytest.approx(3699.3) + assert found["A"]["duration_s"] == pytest.approx(580.3) + assert "B" not in found, "aucune route : la station n’est pas estimée" + + +def test_provider_google_requires_key_and_parses_matrix(monkeypatch): + monkeypatch.setattr(routing, "GOOGLE_KEY", "") + with pytest.raises(ValueError): + routing.provider_google((48.85, 2.35), [("A", 48.86, 2.30)]) + captured = {} + + def fake_get(url, timeout=None, data=None, headers=None): + captured["url"], captured["body"] = url, json.loads(data or b"{}") + return json.dumps( + [ + { + "destinationIndex": 0, + "condition": "ROUTE_EXISTS", + "distanceMeters": 4200, + "duration": "720s", + }, + {"destinationIndex": 1, "condition": "ROUTE_NOT_FOUND"}, + ] + ).encode() + + monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test") + monkeypatch.setattr(routing, "_get", fake_get) + found = routing.provider_google((48.85, 2.35), [("A", 48.86, 2.30), ("B", 48.90, 2.25)]) + assert "computeRouteMatrix" in captured["url"] + assert captured["url"] == "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix" + assert len(captured["body"]["destinations"]) == 2 + assert captured["body"]["travelMode"] == "DRIVE" + assert found == {"A": dict(distance_m=4200.0, duration_s=720.0)} + + +def test_routes_uses_cache_then_provider(store, monkeypatch): + calls = [] + + def fake_provider(origin, targets): + calls.append(targets) + return {station_id: dict(distance_m=5000.0, duration_s=600.0) for station_id, _a, _b in targets} + + monkeypatch.setitem(routing.PROVIDERS, "osrm", fake_provider) + monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "osrm") + origin = (48.85, 2.35) + targets = [("A", 48.86, 2.30)] + first, info = routing.routes(origin, targets) + assert first["A"]["distance_km"] == pytest.approx(5.0) + assert first["A"]["duration_min"] == pytest.approx(10.0) + assert info["provider"] == "osrm" and info["computed"] == 1 and info["from_cache"] == 0 + second, info2 = routing.routes(origin, targets) + assert info2["from_cache"] == 1 and info2["computed"] == 0 + assert len(calls) == 1, "la seconde demande ne doit pas rappeler le fournisseur" + assert store.route_lookup(["|".join(f"{v:.4f}" for v in (*origin, 48.86, 2.30))]) + + +def test_routes_without_provider_says_so_and_invents_nothing(store, monkeypatch): + monkeypatch.setattr(routing, "PROVIDERS", {}) + monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google") + monkeypatch.setattr(routing, "GOOGLE_KEY", "") + routes, info = routing.routes((48.85, 2.35), [("A", 48.86, 2.30)]) + assert routes == {} + assert info["provider"] == "none" + assert "à vol d’oiseau" in info["note"] + + +def test_nearest_stations_applies_radius_on_road_distance(store, monkeypatch): + rows = [ + station_row("proche", 48.8610, 2.3010, price=1.95), + station_row("loin", 48.9000, 2.2500, price=1.80), + station_row("hors", 49.2000, 2.6000, price=1.70), + ] + monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: rows) + + def fake_routes(origin, targets): + distances = {"proche": 1200.0, "loin": 18500.0, "hors": 40000.0} + return ( + { + station_id: dict( + distance_km=distances[station_id] / 1000, duration_min=5.0, provider="osrm", cached=False + ) + for station_id, _lat, _lon in targets + }, + dict(provider="osrm", computed=len(targets), from_cache=0, failures=[], note=""), + ) + + monkeypatch.setattr(routing, "routes", fake_routes) + stations, info = app.nearest_stations(48.86, 2.30, "Gazole", 15) + assert [s.id for s in stations] == ["proche"], "rayon de 15 km appliqué à la distance routière" + assert stations[0].route_distance_km == pytest.approx(1.2) + assert stations[0].route_duration_min == pytest.approx(5.0) + assert stations[0].distance_km < 1, "le vol d’oiseau reste disponible en interne" + assert info["provider"] == "osrm" + + +def test_nearest_stations_without_routing_falls_back_and_says_it(store, monkeypatch): + rows = [station_row("proche", 48.8610, 2.3010), station_row("hors", 49.1000, 2.5000)] + monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: rows) + monkeypatch.setattr( + routing, + "routes", + lambda *args, **kwargs: ( + {}, + dict(provider="none", computed=0, from_cache=0, failures=["TimeoutError"], note="indispo"), + ), + ) + stations, info = app.nearest_stations(48.86, 2.30, "Gazole", 5) + assert [s.id for s in stations] == ["proche"] + assert stations[0].route_distance_km is None + assert info["provider"] == "none" + + +def test_navigation_links_use_exact_coordinates(): + links = app.navigation_links(48.861012, 2.301045) + assert links["coordinates"] == "48.861012,2.301045" + assert links["google_maps"].startswith("https://www.google.com/maps/dir/?api=1&destination=") + assert "48.861012,2.301045" in links["google_maps"] and "travelmode=driving" in links["google_maps"] + assert links["waze"].startswith("https://waze.com/ul?ll=48.861012,2.301045") + + +def test_station_payload_carries_detour_ready_fields(store, monkeypatch): + monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [station_row("A", 48.861, 2.301)]) + monkeypatch.setattr( + routing, + "routes", + lambda *args, **kwargs: ( + {"A": dict(distance_km=3.4, duration_min=8.0, provider="osrm", cached=False)}, + dict(provider="osrm", computed=1, from_cache=0, failures=[], note=""), + ), + ) + monkeypatch.setattr(app.collector, "ensure_fresh_local", lambda **kwargs: dict(refreshed=False)) + monkeypatch.setattr(app.promotions, "active", lambda: []) + monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [station_row("A", 48.861, 2.301)]) + out = app.advice(48.86, 2.30, "Gazole", 15) + station = out["stations"][0] + assert station["route_distance_km"] == pytest.approx(3.4) + assert station["route_duration_min"] == pytest.approx(8.0) + assert station["navigation"]["waze"] + assert out["detour_prep"]["available"] is True + assert out["routing"]["provider"] == "osrm" diff --git a/tests/test_synthesis.py b/tests/test_synthesis.py new file mode 100644 index 0000000..36ad44a --- /dev/null +++ b/tests/test_synthesis.py @@ -0,0 +1,250 @@ +"""Synthèse amont : pression, facteurs en langage courant, « En clair » et prudence.""" + +from datetime import date, timedelta + +import pytest + +import news +import promotions +import storage +import synthesis + + +def seed(series, unit, rows): + return storage.save_upstream(series, rows, unit, "test") + + +def days_ago(n): + return (date.today() - timedelta(days=n)).isoformat() + + +def test_factors_report_unknown_without_data(store): + built = synthesis.build("Gazole") + assert len(built["factors"]) == 6 + assert built["pressure"] == "INCERTAINE" + assert built["confidence"] is None + assert all(factor["arrow"] == "?" for factor in built["factors"]) + assert "pas assez de données" in built["plain"] + assert "pas encore" in built["plain"] and "prévision" in built["disclaimer"] + + +def test_brut_factor_detects_a_rise_and_a_fall(store): + seed( + "brent_eur_daily", + "EUR/baril", + [ + dict(day=days_ago(9), value=80.0), + dict(day=days_ago(3), value=84.0), + dict(day=days_ago(1), value=88.0), + ], + ) + factor = synthesis.factor_brut() + assert factor["direction"] == synthesis.UP + assert factor["arrow"] == "↑" + assert factor["change_pct"] == pytest.approx(10.0) + assert factor["fresh"] is True + assert factor["observed_at"] == days_ago(1) + seed( + "brent_eur_daily", "EUR/baril", [dict(day=days_ago(8), value=88.0), dict(day=days_ago(1), value=72.0)] + ) + fall = synthesis.factor_brut() + assert fall["direction"] == synthesis.DOWN and fall["arrow"] == "↓" + + +def test_brut_factor_marks_stale_data_and_flat_move(store): + seed( + "brent_eur_daily", + "EUR/baril", + [dict(day=days_ago(18), value=80.0), dict(day=days_ago(12), value=80.4)], + ) + factor = synthesis.factor_brut() + assert factor["direction"] == synthesis.FLAT, "variation sous le seuil : peu d’effet" + assert factor["fresh"] is False and factor["age_days"] >= 11 + + +def test_change_factor_inverts_direction(store): + # Un euro plus faible (USD/EUR en hausse) renchérit le baril : pression haussière. + seed("usd_per_eur", "USD/EUR", [dict(day=days_ago(6), value=1.10), dict(day=days_ago(1), value=1.16)]) + factor = synthesis.factor_change() + assert factor["direction"] == synthesis.UP + assert factor["change_pct"] > 0 + + +def test_logistique_factor_reads_chokepoint_traffic(store): + rows = [] + for index in range(6): + rows.append( + ( + "Strait of Hormuz", + dict( + day=days_ago(25 - index * 4), + transit_tankers=40, + transit_total=90, + capacity_tankers=1000, + capacity_total=2000, + ), + ) + ) + rows.append( + ( + "Strait of Hormuz", + dict( + day=days_ago(1), + transit_tankers=22, + transit_total=60, + capacity_tankers=600, + capacity_total=1200, + ), + ) + ) + storage.save_chokepoints(rows, "IMF PortWatch") + factor = synthesis.factor_logistique() + assert factor["direction"] == synthesis.UP, "moins de pétroliers : approvisionnement tendu" + assert "Hormuz" in factor["evidence_text"] + assert "PortWatch" in factor["source"] + + +def test_evenements_factor_weighs_confidence_and_expiry(store): + base = dict( + topic="ormuz", + event_type="chokepoint", + magnitude="forte", + fuels=["gazole"], + zone="Ormuz", + horizon_days=10, + observed_at=days_ago(1), + published_at=days_ago(1), + source_url="https://exemple.fr/a", + extracted_by="test", + ) + storage.save_news_event( + dict( + base, + url_hash="h1", + direction="hausse", + confidence=0.9, + valid_from=days_ago(1), + valid_until=days_ago(-5), + ) + ) + storage.save_news_event( + dict( + base, + url_hash="h2", + direction="baisse", + confidence=0.2, + valid_from=days_ago(1), + valid_until=days_ago(-5), + ) + ) + factor = synthesis.factor_evenements() + assert factor["direction"] == synthesis.UP + assert factor["count"] == 2 and factor["confidence_used"] == pytest.approx(1.1) + # Un événement expiré ne doit plus peser. + storage.save_news_event( + dict( + base, + url_hash="h3", + direction="baisse", + confidence=1.0, + valid_from=days_ago(20), + valid_until=days_ago(5), + ) + ) + assert synthesis.factor_evenements()["direction"] == synthesis.UP + + +def test_pressure_aggregates_weights_and_confidence(store): + seed( + "brent_eur_daily", "EUR/baril", [dict(day=days_ago(9), value=80.0), dict(day=days_ago(1), value=92.0)] + ) + seed( + "dgec_margin_eur_per_tonne", + "EUR/tonne", + [dict(day=days_ago(40), value=200.0), dict(day=days_ago(2), value=260.0)], + ) + built = synthesis.build("Gazole") + assert built["pressure"] == "HAUSSE" + assert built["confidence"] is not None and 0 < built["confidence"] <= 0.8 + assert built["known_factors"] >= 2 + up = [f["label"] for f in built["factors"] if f["direction"] == "up"] + assert "Pétrole brut" in up + assert "montent" in built["plain"] and "pèse le plus" in built["plain"] + assert "jamais comme une prévision validée" in built["plain"] + assert "délai de transmission" in built["plain"] + + +def test_prefilter_rejects_non_fuel_articles_and_duplicates(): + keep, dropped = news.prefilter( + [ + dict( + hash="a", + title="Le détroit d’Ormuz perturbe les livraisons de pétrole brut", + summary="Les pétroliers ralentissent.", + ), + dict(hash="b", title="Recette de gâteau au chocolat", summary="Sucre et farine."), + dict( + hash="c", + title="Le détroit d’Ormuz perturbe les livraisons de pétrole brut", + summary="Doublon du même flux.", + ), + dict(hash="d", title="Nouvelle taxe carburant", summary="Le gazole et l’essence concernés."), + ] + ) + assert [article["hash"] for article in keep] == ["a", "d"] + reasons = {article["hash"]: reason for article, reason in dropped} + assert "carburant" in reasons["b"] + assert "déjà vu" in reasons["c"] + + +def test_prefilter_promotions_needs_brand_and_fuel_words(): + keep, dropped = promotions.prefilter( + [ + dict( + hash="p1", + title="Carburant à prix coûtant chez E.Leclerc ce week-end", + summary="Le gazole au prix coûtant samedi.", + ), + dict(hash="p2", title="E.Leclerc ouvre un nouveau magasin", summary="Ouverture lundi."), + ] + ) + assert [article["hash"] for article in keep] == ["p1"] + assert dropped[0][1], "une raison d’écartement est toujours fournie" + + +def test_queue_metrics_expose_backlog_age_and_durations(store): + storage.save_articles( + [ + dict( + hash="a", + url="https://exemple.fr/a", + title="Ormuz", + source="Test", + published_at=days_ago(3), + observed_at=days_ago(3), + ) + ], + "geo", + ) + storage.save_articles( + [ + dict( + hash="b", + url="https://exemple.fr/b", + title="Suez", + source="Test", + published_at=days_ago(1), + observed_at=days_ago(1), + ) + ], + "geo", + ) + storage.mark_skipped(["b"], "préfiltrage automatique") + storage.record_llm_run("x", "ormuz", "gemma4:12b", 40.0, ok=True) + storage.record_llm_run("y", "ormuz", "gemma4:12b", 60.0, ok=False, detail="TimeoutError") + queue = storage.llm_queue() + assert queue["pending"] == 1 and queue["skipped"] == 1 and queue["total"] == 2 + assert queue["oldest_pending_at"] and queue["oldest_pending_age_hours"] is not None + assert queue["analysed_24h_avg_seconds"] == pytest.approx(50.0) + assert queue["analysed_24h_failures"] == 1 + assert queue["by_model"][0]["model"] == "gemma4:12b" diff --git a/ui.js b/ui.js index f7c652f..27e1bf0 100644 --- a/ui.js +++ b/ui.js @@ -91,13 +91,17 @@ function stationCards(rows){ function render(d){ const s=d.local_stats||{},h=d.history||{}; const fresh=d.local_refresh&&d.local_refresh.refreshed?`Flux actualisé à l’instant`:(d.local_refresh&&Number.isFinite(d.local_refresh.age_seconds)?`Flux lu il y a ${num(d.local_refresh.age_seconds/60,0)} min`:''); - const stations=(d.stations||[]).map(s=>`
${esc(s.city)} · ${num(s.distance_km,1)} km à vol d’oiseau
Déclaré : ${esc(s.updated)}
${esc(s.city)} · ${distance}
Déclaré : ${esc(s.updated)}
${nav}${esc(d.price_warning)}
`:''}${d.brands_warning?`${esc(d.brands_warning)}
`:''}${s.count?`${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.
${esc(d.distance_note)} Un bon prix local ne signifie pas que c’est le bon moment pour remplir le réservoir.
${esc(d.price_warning)}
`:''}${d.routing?.provider==='none'?`${esc(d.routing?.note||'Routage indisponible')}
`:''}${d.brands_warning?`${esc(d.brands_warning)}
`:''}${s.count?`${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.
${esc(d.distance_note)} Un bon prix local ne signifie pas que c’est le bon moment pour remplir le réservoir.
${esc(h.summary)}
${h.confidence==='limited'?'Panel réduit : tendance peu représentative du secteur.
':''}${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.
${esc(d.market?.summary||'Cotation indisponible')}
${d.market?.reference?esc(d.market.reference):''}
${upstreamBlock()}${promotionsBlock(d.promotions,d.promotions_note)}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é.
${esc(d.market?.summary||'Cotation indisponible')} ${d.market?.reference?esc(d.market.reference):''}
${technicalBlock()}${promotionsBlock(d.promotions,d.promotions_note)}Plus ancien non analysé : ${q.oldest_pending_at?stamp(q.oldest_pending_at)+` (${q.oldest_pending_age_hours} h)`:'—'}
+Analysés sur 24 h : ${q.analysed_24h||0} · durée moyenne ${q.analysed_24h_avg_seconds?num(q.analysed_24h_avg_seconds,1)+' s':'—'} · maximum ${q.analysed_24h_max_seconds?num(q.analysed_24h_max_seconds,1)+' s':'—'} · échecs ${q.analysed_24h_failures||0}
+Articles écartés par le préfiltrage (aucun modèle appelé) : ${q.skipped||0} sur ${q.total||0} collectés
+ ${(q.by_model||[]).map(m=>`${esc(m.model)} : ${m.n} analyse(s), ${m.avg_s?num(m.avg_s,1):'—'} s en moyenne, ${m.fails||0} échec(s)
`).join('')}${esc(job.source)}
@@ -115,6 +125,15 @@ async function loadJobs(){ ${job.detail?`${esc(job.detail)}
`:''}'+esc(e.message)+'
';} } +function synthesisBlock(s){ + if(!s)return ''; + const conf=(s.confidence===null||s.confidence===undefined)?'':`confiance ${num(s.confidence*100,0)} %`; + const factors=(s.factors||[]).map(f=>`${esc(f.direction_text)}
${esc(f.explanation)}
${f.evidence_text?`${esc(f.evidence_text)}
`:''}${f.age_days!==null&&f.age_days!==undefined?`Donnée datée du ${esc(String(f.observed_at||'—'))} (${f.age_days} j), source : ${esc(f.source||'—')}
`:''}${esc(s.plain||'')}
${esc(s.disclaimer||'')}
`; +} +function technicalBlock(){ + return `Valeurs brutes, unités, dates, fraîcheur et sources. Ces indicateurs alimentent la synthèse ci-dessus ; ils ne décident pas du conseil.
${esc(p.nature.replace('_',' '))}${p.discount_per_liter?` · ${num(p.discount_per_liter,3)} €/L`:''}${p.fuels?` · ${esc(p.fuels)}`:''} · ${esc(p.state)}
${p.valid_from?`du ${esc(p.valid_from)}`:''}${p.valid_until?` au ${esc(p.valid_until)}`:''}${p.stations?` · ${esc(p.stations)}`:''}
${esc(p.source_url)} · confiance ${p.confidence!==null&&p.confidence!==undefined?num(p.confidence*100,0)+' %':'—'}