Refonte conseil carburant : favoris, historique quotidien et autonomie
Sépare le choix de la station du moment de ravitailler. Ajoute favoris et véhicules persistants, collecte quotidienne avec relance en cas déchec, historique par panel constant, marge de sécurité par véhicule et saisie systématique de lautonomie restante. Retire le score arbitraire, les appels Ollama et les RSS. Stooq indisponible => tendance inconnue.
This commit is contained in:
641
app.py
641
app.py
@@ -1,108 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Conseiller carburant local, sans dépendance externe.
|
||||
"""Conseiller carburant : prix publics, profils explicites et décisions prudentes."""
|
||||
|
||||
Sources best-effort : prix-carburants.gouv.fr, Stooq/Yahoo compatibles CSV,
|
||||
flux RSS Google News. Les erreurs de collecte n'empêchent pas l'avis local.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from http import HTTPStatus
|
||||
from datetime import date, datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
APP_DIR = Path(os.environ.get("FUEL_ADVISOR_DIR", "/opt/fuel-advisor"))
|
||||
import collector
|
||||
import storage
|
||||
from decision import recommend
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent
|
||||
DATA_DIR = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor"))
|
||||
CACHE_DB = DATA_DIR / "fuel.sqlite3"
|
||||
HOST = os.environ.get("FUEL_ADVISOR_HOST", "0.0.0.0")
|
||||
PORT = int(os.environ.get("FUEL_ADVISOR_PORT", "8003"))
|
||||
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://10.53.2.22:11434")
|
||||
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:12b")
|
||||
FUEL_URL = os.environ.get(
|
||||
"FUEL_PRICES_URL", "https://donnees.roulez-eco.fr/opendata/instantane"
|
||||
)
|
||||
MARKET_URL = os.environ.get(
|
||||
"FUEL_MARKET_URL", "https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv"
|
||||
)
|
||||
NEWS_URL = os.environ.get(
|
||||
"FUEL_NEWS_URL",
|
||||
"https://news.google.com/rss/search?q=carburant%20p%C3%A9trole%20France&hl=fr&gl=FR&ceid=FR:fr",
|
||||
)
|
||||
FUEL_URL = os.environ.get("FUEL_PRICES_URL", "https://donnees.roulez-eco.fr/opendata/instantane")
|
||||
MARKET_URL = os.environ.get("FUEL_MARKET_URL", "https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv")
|
||||
CACHE_TTL = int(os.environ.get("FUEL_CACHE_TTL", "21600"))
|
||||
USER_AGENT = "CortexFuelAdvisor/0.2 (+internal homelab)"
|
||||
FUEL_TYPES = storage.FUELS
|
||||
DEFAULT_FUEL = os.environ.get("FUEL_DEFAULT_TYPE", "Gazole")
|
||||
USER_AGENT = "CortexFuelAdvisor/0.1 (+internal homelab)"
|
||||
FUEL_TYPES = ["Gazole", "SP95", "SP98", "E10", "E85", "GPLc"]
|
||||
FETCH_LOCK = threading.Lock()
|
||||
MARKET_LOCK = threading.Lock()
|
||||
LOG = logging.getLogger("fuel-advisor")
|
||||
|
||||
INDEX_HTML = """<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Conseiller carburant</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; --bg:#08111f; --panel:#0f1d33; --muted:#8ea2bd; --text:#eef5ff; --accent:#5eead4; --warn:#fbbf24; --bad:#fb7185; --ok:#34d399; }
|
||||
*{box-sizing:border-box} body{margin:0;font-family:Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;background:radial-gradient(circle at top left,#12365b 0,#08111f 45%,#050914 100%);color:var(--text);min-height:100vh}
|
||||
main{max-width:1100px;margin:0 auto;padding:32px 18px 48px}.hero{display:grid;gap:18px;margin-bottom:20px}.eyebrow{color:var(--accent);font-weight:700;letter-spacing:.08em;text-transform:uppercase;font-size:12px}.title{font-size:clamp(32px,6vw,64px);line-height:.95;margin:0}.subtitle{color:var(--muted);max-width:760px;font-size:17px}.card{background:rgba(15,29,51,.82);border:1px solid rgba(148,163,184,.18);border-radius:24px;box-shadow:0 24px 80px rgba(0,0,0,.35);padding:22px;backdrop-filter:blur(10px)}
|
||||
.grid{display:grid;grid-template-columns:1fr;gap:16px}@media(min-width:850px){.grid{grid-template-columns:380px 1fr}}
|
||||
label{display:block;color:#c7d2fe;font-weight:650;margin-bottom:8px}select,input{width:100%;border:1px solid rgba(148,163,184,.22);border-radius:14px;background:#091426;color:var(--text);padding:12px 14px;font-size:15px}button{border:0;border-radius:14px;background:linear-gradient(135deg,#2dd4bf,#60a5fa);color:#04111f;font-weight:800;padding:13px 16px;cursor:pointer}button.secondary{background:#172641;color:#dbeafe;border:1px solid rgba(148,163,184,.22)}.row{display:grid;grid-template-columns:1fr 1fr;gap:12px}.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:14px}.status{color:var(--muted);font-size:14px;margin-top:12px;min-height:20px}.score{font-size:46px;font-weight:900;margin:0}.pill{display:inline-flex;align-items:center;border-radius:999px;padding:7px 10px;background:#172641;color:#dbeafe;font-size:13px;margin:3px}.buy{color:var(--ok)}.wait{color:var(--warn)}.avoid{color:var(--bad)}.stations{display:grid;gap:10px;margin-top:12px}.station{display:grid;gap:4px;padding:13px;border-radius:16px;background:#0b1729;border:1px solid rgba(148,163,184,.14)}.station strong{font-size:16px}.muted{color:var(--muted)}.big{font-size:22px;font-weight:900}.news{margin:8px 0 0 18px;color:#cbd5e1}.footer{margin-top:18px;color:#7890ad;font-size:12px}
|
||||
</style>
|
||||
</head>
|
||||
<body><main>
|
||||
<section class="hero"><div class="eyebrow">Cortex Lab · Carburant</div><h1 class="title">Acheter maintenant ou attendre ?</h1><div class="subtitle">L’application croise les prix locaux autour du téléphone, une tendance marché pétrole et des signaux d’actualité. La recommandation reste indicative : elle favorise le meilleur prix local mesurable.</div></section>
|
||||
<section class="grid">
|
||||
<div class="card"><label>Carburant</label><select id="fuel"></select><div class="row" style="margin-top:12px"><div><label>Rayon km</label><input id="radius" type="number" value="15" min="1" max="80"></div><div><label>Position ou adresse</label><input id="place" value="" placeholder="ex. Nantes, rue…, ou géoloc"></div></div><div class="actions"><button id="locate">Me géolocaliser</button><button class="secondary" id="search">Chercher adresse</button><button class="secondary" id="demo">Autour Paris</button></div><div class="status" id="status">Clique sur géolocaliser ou saisis une ville/adresse.</div></div>
|
||||
<div class="card" id="result"><div class="muted">Aucun calcul pour l’instant.</div></div>
|
||||
</section><div class="footer">Données : prix-carburants.gouv.fr, flux marché/RSS best-effort, aucune position persistée côté navigateur.</div>
|
||||
</main><script>
|
||||
const fuels = %FUEL_TYPES%; const fuelSel=document.getElementById('fuel'); let lastCoords=null; fuels.forEach(f=>{const o=document.createElement('option');o.value=f;o.textContent=f; if(f==='%DEFAULT_FUEL%') o.selected=true; fuelSel.appendChild(o)});
|
||||
async function advise(lat, lon){
|
||||
lastCoords={lat,lon};
|
||||
document.getElementById('place').value = lat.toFixed(4)+', '+lon.toFixed(4);
|
||||
const radius=document.getElementById('radius').value || 15, fuel=fuelSel.value;
|
||||
document.getElementById('status').textContent='Collecte des prix et calcul en cours…';
|
||||
const r=await fetch(`/api/advice?lat=${lat}&lon=${lon}&radius_km=${radius}&fuel=${encodeURIComponent(fuel)}`);
|
||||
const data=await r.json(); render(data); document.getElementById('status').textContent=data.generated_at ? 'Avis calculé à '+data.generated_at : 'Terminé';
|
||||
}
|
||||
function klass(a){return a==='buy'?'buy':a==='wait'?'wait':'avoid'}
|
||||
function render(d){
|
||||
if(d.error){document.getElementById('result').innerHTML=`<div class="avoid big">${d.error}</div><p class="muted">${d.detail||''}</p>`;return}
|
||||
const stations=(d.stations||[]).map(s=>`<div class="station"><strong>${s.name}</strong><span class="muted">${s.city||''} · ${s.distance_km} km · màj ${s.updated||'N/A'}</span><span class="big">${s.price.toFixed(3)} €/L</span><span class="muted">${s.address||''}</span></div>`).join('');
|
||||
const reasons=(d.reasons||[]).map(x=>`<span class="pill">${x}</span>`).join('');
|
||||
const news=(d.news||[]).map(n=>`<li>${n}</li>`).join('');
|
||||
const stats=d.local_stats||{};
|
||||
const buckets=(stats.price_buckets||[]).map(b=>`<span class="pill">${b.price.toFixed(3)} €/L · ${b.count}</span>`).join('');
|
||||
const tie=stats.best_tie_count>1?`<p class="muted">${stats.best_tie_count} stations sont à égalité au meilleur prix affiché (${stats.best.toFixed(3)} €/L). Les stations ci-dessous sont les moins chères, pas toutes les stations du rayon.</p>`:'';
|
||||
document.getElementById('result').innerHTML=`<div class="eyebrow">Recommandation</div><h2 class="score ${klass(d.action)}">${d.label}</h2><p>${d.summary}</p><div>${reasons}</div><h3>Résumé local</h3><p class="muted">${stats.count||0} stations comparées · min ${stats.min?.toFixed(3)||'N/A'} €/L · médiane ${stats.median?.toFixed(3)||'N/A'} €/L · max ${stats.max?.toFixed(3)||'N/A'} €/L</p><div>${buckets}</div>${tie}<h3>Stations les moins chères</h3><div class="stations">${stations||'<span class="muted">Aucune station locale trouvée.</span>'}</div><h3>Signaux externes</h3><p class="muted">Marché: ${d.market?.summary||'indisponible'} · IA: ${d.ai_used?'utilisée':'non utilisée'}</p>${news?`<ul class="news">${news}</ul>`:''}`;
|
||||
}
|
||||
async function geocode(){
|
||||
const q=document.getElementById('place').value.trim();
|
||||
if(!q){document.getElementById('status').textContent='Saisis une ville ou une adresse.';return}
|
||||
document.getElementById('status').textContent='Recherche de la position…';
|
||||
const r=await fetch(`/api/geocode?q=${encodeURIComponent(q)}`); const d=await r.json();
|
||||
if(d.error){document.getElementById('status').textContent=d.error;return}
|
||||
advise(d.lat,d.lon);
|
||||
}
|
||||
document.getElementById('locate').onclick=()=>navigator.geolocation.getCurrentPosition(p=>advise(p.coords.latitude,p.coords.longitude),e=>document.getElementById('status').textContent='Géolocalisation refusée/HTTP non sécurisé. Saisis une ville ou adresse puis clique Chercher adresse.',{enableHighAccuracy:true,timeout:12000});
|
||||
document.getElementById('search').onclick=geocode;
|
||||
document.getElementById('place').addEventListener('keydown', e=>{if(e.key==='Enter') geocode()});
|
||||
fuelSel.addEventListener('change', ()=>{ if(lastCoords) advise(lastCoords.lat,lastCoords.lon); });
|
||||
document.getElementById('radius').addEventListener('change', ()=>{ if(lastCoords) advise(lastCoords.lat,lastCoords.lon); });
|
||||
document.getElementById('demo').onclick=()=>advise(48.8566,2.3522);
|
||||
</script></body></html>"""
|
||||
|
||||
@dataclass
|
||||
class Station:
|
||||
@@ -117,105 +54,106 @@ class Station:
|
||||
distance_km: float
|
||||
|
||||
|
||||
def now_iso() -> str:
|
||||
return datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M")
|
||||
def now_iso():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def ensure_db() -> None:
|
||||
def ensure_db():
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with sqlite3.connect(CACHE_DB) as db:
|
||||
db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT NOT NULL, ts INTEGER NOT NULL)")
|
||||
with sqlite3.connect(CACHE_DB, timeout=20) as db:
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT NOT NULL, ts INTEGER NOT NULL)"
|
||||
)
|
||||
|
||||
|
||||
def cache_get(key: str, ttl: int = CACHE_TTL) -> Any | None:
|
||||
def cache_get(key, ttl=CACHE_TTL):
|
||||
ensure_db()
|
||||
with sqlite3.connect(CACHE_DB) as db:
|
||||
row = db.execute("SELECT value, ts FROM cache WHERE key=?", (key,)).fetchone()
|
||||
if not row or int(time.time()) - row[1] > ttl:
|
||||
with sqlite3.connect(CACHE_DB, timeout=20) as db:
|
||||
row = db.execute("SELECT value,ts FROM cache WHERE key=?", (key,)).fetchone()
|
||||
if not row or time.time() - row[1] > ttl:
|
||||
return None
|
||||
return json.loads(row[0])
|
||||
|
||||
|
||||
def cache_set(key: str, value: Any) -> None:
|
||||
def cache_set(key, value):
|
||||
ensure_db()
|
||||
with sqlite3.connect(CACHE_DB) as db:
|
||||
with sqlite3.connect(CACHE_DB, timeout=20) as db:
|
||||
db.execute(
|
||||
"REPLACE INTO cache(key,value,ts) VALUES(?,?,?)",
|
||||
(key, json.dumps(value, ensure_ascii=False), int(time.time())),
|
||||
"REPLACE INTO cache VALUES(?,?,?)", (key, json.dumps(value, ensure_ascii=False), int(time.time()))
|
||||
)
|
||||
|
||||
|
||||
def fetch_bytes(url: str, timeout: int = 20) -> bytes:
|
||||
def fetch_bytes(url, timeout=20):
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.read()
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
raw = response.read(50_000_001)
|
||||
if len(raw) > 50_000_000:
|
||||
raise ValueError("Source trop volumineuse")
|
||||
return raw
|
||||
|
||||
|
||||
def load_fuel_data() -> list[dict[str, Any]]:
|
||||
cached = cache_get("fuel_data")
|
||||
if cached is not None:
|
||||
return cached
|
||||
raw = fetch_bytes(FUEL_URL, 45)
|
||||
if raw[:2] == b"PK":
|
||||
with zipfile.ZipFile(io.BytesIO(raw)) as zf:
|
||||
name = next(n for n in zf.namelist() if n.lower().endswith(".xml"))
|
||||
xml_data = zf.read(name)
|
||||
else:
|
||||
xml_data = raw
|
||||
root = ET.fromstring(xml_data)
|
||||
rows: list[dict[str, Any]] = []
|
||||
for pdv in root.findall(".//pdv"):
|
||||
try:
|
||||
lat = float(pdv.attrib.get("latitude", "0")) / 100000
|
||||
lon = float(pdv.attrib.get("longitude", "0")) / 100000
|
||||
except ValueError:
|
||||
continue
|
||||
prices = {}
|
||||
updates = {}
|
||||
for prix in pdv.findall("prix"):
|
||||
nom = prix.attrib.get("nom")
|
||||
val = prix.attrib.get("valeur")
|
||||
if not nom or not val:
|
||||
continue
|
||||
def load_fuel_data(force=False):
|
||||
with FETCH_LOCK:
|
||||
cached = None if force else cache_get("fuel_data")
|
||||
if cached is not None:
|
||||
return cached
|
||||
raw = fetch_bytes(FUEL_URL, 45)
|
||||
if raw[:2] == b"PK":
|
||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||
name = next(n for n in archive.namelist() if n.lower().endswith(".xml"))
|
||||
if archive.getinfo(name).file_size > 100_000_000:
|
||||
raise ValueError("Archive trop volumineuse")
|
||||
raw = archive.read(name)
|
||||
root = ET.fromstring(raw)
|
||||
rows = []
|
||||
for pdv in root.findall(".//pdv"):
|
||||
try:
|
||||
parsed = float(val)
|
||||
prices[nom] = parsed / 1000 if parsed > 10 else parsed
|
||||
updates[nom] = prix.attrib.get("maj", "")
|
||||
except ValueError:
|
||||
pass
|
||||
if prices:
|
||||
rows.append(
|
||||
{
|
||||
"id": pdv.attrib.get("id", ""),
|
||||
"name": pdv.findtext("adresse", "Station-service"),
|
||||
"address": pdv.findtext("adresse", ""),
|
||||
"city": pdv.findtext("ville", ""),
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"prices": prices,
|
||||
"updates": updates,
|
||||
}
|
||||
)
|
||||
cache_set("fuel_data", rows)
|
||||
return rows
|
||||
lat = storage.number(float(pdv.attrib["latitude"]) / 100000, "Latitude", -90, 90)
|
||||
lon = storage.number(float(pdv.attrib["longitude"]) / 100000, "Longitude", -180, 180)
|
||||
except (ValueError, KeyError):
|
||||
continue
|
||||
prices, updates = {}, {}
|
||||
ruptures = {r.attrib.get("nom") for r in pdv.findall("rupture") if not r.attrib.get("fin")}
|
||||
for prix in pdv.findall("prix"):
|
||||
fuel = prix.attrib.get("nom")
|
||||
if fuel not in FUEL_TYPES or fuel in ruptures:
|
||||
continue
|
||||
try:
|
||||
value = float(prix.attrib["valeur"])
|
||||
value = value / 1000 if value > 10 else value
|
||||
prices[fuel] = storage.number(value, "Prix", 0.01, 10)
|
||||
updates[fuel] = prix.attrib.get("maj", "")
|
||||
except (ValueError, KeyError):
|
||||
continue
|
||||
if prices:
|
||||
rows.append(
|
||||
dict(
|
||||
id=pdv.attrib.get("id", ""),
|
||||
name=pdv.findtext("adresse", "Station-service"),
|
||||
address=pdv.findtext("adresse", ""),
|
||||
city=pdv.findtext("ville", ""),
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
prices=prices,
|
||||
updates=updates,
|
||||
)
|
||||
)
|
||||
if not rows:
|
||||
raise ValueError("Aucune station exploitable dans la source")
|
||||
cache_set("fuel_data", rows)
|
||||
return rows
|
||||
|
||||
|
||||
def haversine(a_lat: float, a_lon: float, b_lat: float, b_lon: float) -> float:
|
||||
r = 6371.0
|
||||
p1, p2 = math.radians(a_lat), math.radians(b_lat)
|
||||
dphi = math.radians(b_lat - a_lat)
|
||||
dl = math.radians(b_lon - a_lon)
|
||||
q = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
||||
return 2 * r * math.atan2(math.sqrt(q), math.sqrt(1 - q))
|
||||
haversine = storage.distance_km
|
||||
|
||||
|
||||
def nearest_stations(lat: float, lon: float, fuel: str, radius_km: float) -> list[Station]:
|
||||
def nearest_stations(lat, lon, fuel, radius_km):
|
||||
stations = []
|
||||
for row in load_fuel_data():
|
||||
if fuel not in row["prices"]:
|
||||
if fuel not in row["prices"] or not storage.fresh_price(row["updates"].get(fuel, "")):
|
||||
continue
|
||||
d = haversine(lat, lon, row["lat"], row["lon"])
|
||||
if d <= radius_km:
|
||||
distance = haversine(lat, lon, row["lat"], row["lon"])
|
||||
if distance <= radius_km:
|
||||
stations.append(
|
||||
Station(
|
||||
id=row["id"],
|
||||
@@ -226,208 +164,245 @@ def nearest_stations(lat: float, lon: float, fuel: str, radius_km: float) -> lis
|
||||
lon=row["lon"],
|
||||
price=row["prices"][fuel],
|
||||
updated=row["updates"].get(fuel, ""),
|
||||
distance_km=round(d, 1),
|
||||
distance_km=round(distance, 1),
|
||||
)
|
||||
)
|
||||
return sorted(stations, key=lambda s: (s.price, s.distance_km))
|
||||
|
||||
|
||||
def market_signal() -> dict[str, Any]:
|
||||
cached = cache_get("market", 3600)
|
||||
if cached is not None:
|
||||
return cached
|
||||
result = {"summary": "indisponible", "trend": "flat", "delta_pct": 0.0}
|
||||
try:
|
||||
text = fetch_bytes(MARKET_URL, 12).decode("utf-8", "ignore")
|
||||
rows = list(csv.DictReader(io.StringIO(text)))
|
||||
if rows:
|
||||
def market_signal():
|
||||
with MARKET_LOCK:
|
||||
cached = cache_get("market_v2", 3600)
|
||||
if cached is not None:
|
||||
return cached
|
||||
result = dict(
|
||||
summary="Pétrole indisponible — tendance inconnue",
|
||||
trend="unknown",
|
||||
delta_pct=None,
|
||||
source="Stooq (flux configuré)",
|
||||
date=None,
|
||||
)
|
||||
try:
|
||||
rows = list(csv.DictReader(io.StringIO(fetch_bytes(MARKET_URL, 5).decode("utf-8", "replace"))))
|
||||
if not rows:
|
||||
raise ValueError("Flux vide")
|
||||
row = rows[-1]
|
||||
close = float(row.get("Close") or 0)
|
||||
open_ = float(row.get("Open") or close)
|
||||
delta = ((close - open_) / open_ * 100) if open_ else 0
|
||||
quote_day = date.fromisoformat(row.get("Date", ""))
|
||||
if not 0 <= (datetime.now(timezone.utc).date() - quote_day).days <= 4:
|
||||
raise ValueError("Cours périmé")
|
||||
close = storage.number(row.get("Close"), "Dernier cours", 0.01, 10000)
|
||||
opening = storage.number(row.get("Open"), "Ouverture", 0.01, 10000)
|
||||
delta = (close - opening) / opening * 100
|
||||
trend = "up" if delta > 0.7 else "down" if delta < -0.7 else "flat"
|
||||
result = {"summary": f"pétrole {trend} ({delta:+.1f}%)", "trend": trend, "delta_pct": round(delta, 2)}
|
||||
symbol = str(row.get("Symbol", "pétrole"))[:30]
|
||||
result.update(
|
||||
summary=f"{symbol} : {close:.2f} USD/baril, {delta:+.1f}% depuis l’ouverture ({quote_day}). Signal intrajournalier, pas une prévision à la pompe.",
|
||||
trend=trend,
|
||||
delta_pct=round(delta, 2),
|
||||
price_usd=close,
|
||||
date=quote_day.isoformat(),
|
||||
)
|
||||
except Exception as exc:
|
||||
result["error"] = type(exc).__name__
|
||||
cache_set("market_v2", result)
|
||||
return result
|
||||
|
||||
|
||||
def geocode_address(query):
|
||||
# Une recherche non enregistrée n'est pas conservée dans le cache SQL.
|
||||
params = urllib.parse.urlencode(dict(q=query, format="jsonv2", limit=1, countrycodes="fr"))
|
||||
rows = json.loads(fetch_bytes("https://nominatim.openstreetmap.org/search?" + params, 12))
|
||||
if not rows:
|
||||
raise ValueError("Adresse introuvable")
|
||||
return dict(
|
||||
lat=float(rows[0]["lat"]), lon=float(rows[0]["lon"]), label=rows[0].get("display_name", query)
|
||||
)
|
||||
|
||||
|
||||
def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None):
|
||||
hist = storage.history(lat, lon, radius_km, fuel)
|
||||
result = recommend(vehicle, remaining_km, hist, trip)
|
||||
stations, error = [], None
|
||||
try:
|
||||
stations = nearest_stations(lat, lon, fuel, radius_km)
|
||||
except Exception as exc:
|
||||
result["summary"] = f"indisponible ({exc.__class__.__name__})"
|
||||
cache_set("market", result)
|
||||
LOG.warning("Source des prix inaccessible : %s", type(exc).__name__)
|
||||
error = "Source des prix inaccessible ; aucun ancien prix présenté comme actuel."
|
||||
prices = [s.price for s in stations]
|
||||
stats = {}
|
||||
if prices:
|
||||
stats = dict(
|
||||
count=len(prices),
|
||||
best=prices[0],
|
||||
min=min(prices),
|
||||
max=max(prices),
|
||||
average=round(statistics.mean(prices), 3),
|
||||
median=round(statistics.median(prices), 3),
|
||||
best_tie_count=prices.count(prices[0]),
|
||||
price_buckets=[dict(price=p, count=prices.count(p)) for p in sorted(set(prices))],
|
||||
)
|
||||
result.update(
|
||||
generated_at=now_iso(),
|
||||
fuel=fuel,
|
||||
history=hist,
|
||||
local_stats=stats,
|
||||
stations=[s.__dict__ for s in stations[:12]],
|
||||
market=market_signal(),
|
||||
ai_used=False,
|
||||
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 ravitailler sont évalués séparément.",
|
||||
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,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def news_signal() -> list[str]:
|
||||
cached = cache_get("news", 7200)
|
||||
if cached is not None:
|
||||
return cached
|
||||
items: list[str] = []
|
||||
try:
|
||||
xml = fetch_bytes(NEWS_URL, 10)
|
||||
root = ET.fromstring(xml)
|
||||
for item in root.findall(".//item")[:5]:
|
||||
title = re.sub(r"\s+-\s+[^-]+$", "", item.findtext("title", "")).strip()
|
||||
if title:
|
||||
items.append(title[:160])
|
||||
except Exception:
|
||||
pass
|
||||
cache_set("news", items)
|
||||
return items
|
||||
|
||||
|
||||
def geocode_address(query: str) -> dict[str, Any]:
|
||||
key = "geocode:" + query.lower().strip()
|
||||
cached = cache_get(key, 604800)
|
||||
if cached is not None:
|
||||
return cached
|
||||
params = urllib.parse.urlencode({"q": query, "format": "jsonv2", "limit": "1", "countrycodes": "fr"})
|
||||
req = urllib.request.Request(
|
||||
"https://nominatim.openstreetmap.org/search?" + params,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=12) as r:
|
||||
rows = json.loads(r.read().decode())
|
||||
if not rows:
|
||||
raise ValueError("Adresse introuvable")
|
||||
out = {"lat": float(rows[0]["lat"]), "lon": float(rows[0]["lon"]), "label": rows[0].get("display_name", query)}
|
||||
cache_set(key, out)
|
||||
return out
|
||||
|
||||
|
||||
def ollama_summary(context: dict[str, Any]) -> tuple[str | None, bool]:
|
||||
prompt = (
|
||||
"Réponds en français en 2 phrases max. Donne un conseil prudent pour acheter du carburant, "
|
||||
"basé uniquement sur ces données JSON. Ne prétends pas connaître l'avenir.\n"
|
||||
+ json.dumps(context, ensure_ascii=False)
|
||||
)
|
||||
payload = json.dumps({"model": OLLAMA_MODEL, "prompt": prompt, "stream": False, "options": {"num_predict": 120}}).encode()
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
urllib.parse.urljoin(OLLAMA_URL.rstrip("/") + "/", "api/generate"),
|
||||
data=payload,
|
||||
headers={"Content-Type": "application/json", "User-Agent": USER_AGENT},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=25) as r:
|
||||
data = json.loads(r.read().decode())
|
||||
summary = str(data.get("response", "")).strip()
|
||||
return summary or None, bool(summary)
|
||||
except Exception:
|
||||
return None, False
|
||||
|
||||
|
||||
def advice(lat: float, lon: float, fuel: str, radius_km: float) -> dict[str, Any]:
|
||||
stations = nearest_stations(lat, lon, fuel, radius_km)
|
||||
if not stations:
|
||||
return {"error": "Aucune station trouvée", "detail": f"Pas de prix {fuel} dans un rayon de {radius_km:g} km."}
|
||||
prices = [s.price for s in stations]
|
||||
best = stations[0]
|
||||
local_avg = sum(prices) / len(prices)
|
||||
median = sorted(prices)[len(prices) // 2]
|
||||
spread = median - best.price
|
||||
market = market_signal()
|
||||
news = news_signal()
|
||||
score = 50
|
||||
reasons = []
|
||||
if spread >= 0.07:
|
||||
score += 25; reasons.append(f"meilleure station {spread:.3f} €/L sous la médiane locale")
|
||||
elif spread >= 0.03:
|
||||
score += 12; reasons.append(f"prix local intéressant ({spread:.3f} €/L sous médiane)")
|
||||
else:
|
||||
score -= 8; reasons.append("écart local faible")
|
||||
if best.price <= local_avg - 0.04:
|
||||
score += 10; reasons.append("sous la moyenne locale")
|
||||
if market["trend"] == "up":
|
||||
score += 12; reasons.append("signal marché en hausse")
|
||||
elif market["trend"] == "down":
|
||||
score -= 12; reasons.append("signal marché en baisse")
|
||||
if len(stations) < 3:
|
||||
score -= 8; reasons.append("peu de stations comparables")
|
||||
action = "buy" if score >= 66 else "wait" if score >= 45 else "avoid"
|
||||
label = "Acheter maintenant" if action == "buy" else "Attendre un peu" if action == "wait" else "Éviter sauf urgence"
|
||||
base_summary = (
|
||||
f"Meilleur prix {fuel}: {best.price:.3f} €/L à {best.distance_km} km. "
|
||||
f"Moyenne locale: {local_avg:.3f} €/L sur {len(stations)} stations."
|
||||
)
|
||||
ai_text, ai_used = ollama_summary({"label": label, "best": best.price, "avg": local_avg, "spread": spread, "market": market, "reasons": reasons})
|
||||
price_counts: dict[str, int] = {}
|
||||
for p in prices:
|
||||
key = f"{p:.3f}"
|
||||
price_counts[key] = price_counts.get(key, 0) + 1
|
||||
best_tie_count = sum(1 for s in stations if round(s.price, 3) == round(best.price, 3))
|
||||
return {
|
||||
"generated_at": now_iso(),
|
||||
"fuel": fuel,
|
||||
"action": action,
|
||||
"label": label,
|
||||
"score": score,
|
||||
"summary": ai_text or base_summary,
|
||||
"reasons": reasons,
|
||||
"market": market,
|
||||
"news": news[:4],
|
||||
"ai_used": ai_used,
|
||||
"local_stats": {
|
||||
"count": len(stations),
|
||||
"best": round(best.price, 3),
|
||||
"best_tie_count": best_tie_count,
|
||||
"average": round(local_avg, 3),
|
||||
"median": round(median, 3),
|
||||
"min": round(min(prices), 3),
|
||||
"max": round(max(prices), 3),
|
||||
"price_buckets": [
|
||||
{"price": float(price), "count": count}
|
||||
for price, count in sorted(price_counts.items(), key=lambda item: float(item[0]))[:12]
|
||||
],
|
||||
},
|
||||
"stations": [s.__dict__ for s in stations[:8]],
|
||||
}
|
||||
def from_payload(data):
|
||||
lat = storage.number(data.get("lat"), "Latitude", -90, 90)
|
||||
lon = storage.number(data.get("lon"), "Longitude", -180, 180)
|
||||
radius = storage.number(data.get("radius_km", 15), "Rayon", 1, 80)
|
||||
vehicle = storage.get_entity("vehicles", int(data["vehicle_id"])) if data.get("vehicle_id") else None
|
||||
fuel = vehicle["fuel"] if vehicle else data.get("fuel", DEFAULT_FUEL)
|
||||
if fuel not in FUEL_TYPES:
|
||||
raise ValueError("Carburant non supporté")
|
||||
trip = data.get("trip")
|
||||
if trip is not None and not isinstance(trip, dict):
|
||||
raise ValueError("Trajet invalide")
|
||||
return advice(lat, lon, fuel, radius, vehicle, data.get("remaining_km"), trip)
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, fmt: str, *args: Any) -> None:
|
||||
print(f"{self.address_string()} - {fmt % args}", flush=True)
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(70)
|
||||
|
||||
def send_json(self, payload: Any, status: HTTPStatus = HTTPStatus.OK) -> None:
|
||||
data = json.dumps(payload, ensure_ascii=False).encode()
|
||||
def log_message(self, fmt, *args):
|
||||
# Pas de query string (géolocalisation/adresse), ni de corps de requête dans les logs.
|
||||
LOG.info("%s %s", self.command, urllib.parse.urlparse(self.path).path)
|
||||
|
||||
def send_body(self, body, content_type, status=200):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers(); self.wfile.write(data)
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Referrer-Policy", "same-origin")
|
||||
self.send_header(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'",
|
||||
)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self) -> None:
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
if parsed.path == "/healthz":
|
||||
return self.send_json({"ok": True, "time": now_iso()})
|
||||
if parsed.path == "/api/geocode":
|
||||
try:
|
||||
q = urllib.parse.parse_qs(parsed.query).get("q", [""])[0].strip()
|
||||
if len(q) < 2:
|
||||
raise ValueError("Adresse trop courte")
|
||||
return self.send_json(geocode_address(q))
|
||||
except Exception as exc:
|
||||
return self.send_json({"error": f"Géocodage impossible: {exc}"}, HTTPStatus.BAD_REQUEST)
|
||||
if parsed.path == "/api/advice":
|
||||
try:
|
||||
q = urllib.parse.parse_qs(parsed.query)
|
||||
lat = float(q.get("lat", [""])[0]); lon = float(q.get("lon", [""])[0])
|
||||
radius = max(1, min(80, float(q.get("radius_km", ["15"])[0])))
|
||||
fuel = q.get("fuel", [DEFAULT_FUEL])[0]
|
||||
def send_json(self, payload, status=200):
|
||||
self.send_body(
|
||||
json.dumps(payload, ensure_ascii=False, allow_nan=False).encode(),
|
||||
"application/json; charset=utf-8",
|
||||
status,
|
||||
)
|
||||
|
||||
def do_GET(self):
|
||||
try:
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
path = parsed.path
|
||||
q = {k: v[0] for k, v in urllib.parse.parse_qs(parsed.query).items()}
|
||||
if path == "/healthz":
|
||||
return self.send_json(dict(ok=True, version=2, time=now_iso()))
|
||||
if path in ("/", "/index.html", "/ui.js", "/style.css"):
|
||||
name = "index.html" if path in ("/", "/index.html") else path[1:]
|
||||
content_type = {
|
||||
"index.html": "text/html; charset=utf-8",
|
||||
"ui.js": "text/javascript; charset=utf-8",
|
||||
"style.css": "text/css; charset=utf-8",
|
||||
}[name]
|
||||
return self.send_body((APP_DIR / name).read_bytes(), content_type)
|
||||
if path == "/api/config":
|
||||
return self.send_json(dict(fuels=FUEL_TYPES, default_fuel=DEFAULT_FUEL))
|
||||
if path == "/api/status":
|
||||
return self.send_json(collector.status())
|
||||
if path in ("/api/vehicles", "/api/favorites"):
|
||||
return self.send_json(dict(items=storage.list_entities(path.split("/")[-1])))
|
||||
if path == "/api/geocode":
|
||||
query = q.get("q", "").strip()
|
||||
if not 2 <= len(query) <= 200:
|
||||
raise ValueError("Adresse requise, 200 caractères maximum")
|
||||
return self.send_json(geocode_address(query))
|
||||
if path == "/api/advice":
|
||||
# Compatibilité comparaison publique, autonomie seulement via POST.
|
||||
q.pop("vehicle_id", None)
|
||||
return self.send_json(from_payload(q))
|
||||
if path == "/api/history":
|
||||
lat = storage.number(q.get("lat"), "Latitude", -90, 90)
|
||||
lon = storage.number(q.get("lon"), "Longitude", -180, 180)
|
||||
radius = storage.number(q.get("radius_km", 15), "Rayon", 1, 80)
|
||||
fuel = q.get("fuel", DEFAULT_FUEL)
|
||||
if fuel not in FUEL_TYPES:
|
||||
raise ValueError("carburant non supporté")
|
||||
return self.send_json(advice(lat, lon, fuel, radius))
|
||||
except Exception as exc:
|
||||
return self.send_json({"error": "Paramètres invalides", "detail": str(exc)}, HTTPStatus.BAD_REQUEST)
|
||||
if parsed.path in ("/", "/index.html"):
|
||||
html = INDEX_HTML.replace("%FUEL_TYPES%", json.dumps(FUEL_TYPES)).replace("%DEFAULT_FUEL%", DEFAULT_FUEL)
|
||||
data = html.encode()
|
||||
self.send_response(HTTPStatus.OK)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers(); self.wfile.write(data); return
|
||||
self.send_error(HTTPStatus.NOT_FOUND)
|
||||
raise ValueError("Carburant invalide")
|
||||
return self.send_json(storage.history(lat, lon, radius, fuel))
|
||||
return self.send_json(dict(error="Route introuvable"), 404)
|
||||
except Exception as exc:
|
||||
self.handle_error(exc)
|
||||
|
||||
def handle_error(self, exc):
|
||||
if isinstance(exc, (ValueError, TypeError)):
|
||||
self.send_json(dict(error=str(exc)), 400)
|
||||
elif isinstance(exc, LookupError):
|
||||
self.send_json(dict(error=str(exc)), 404)
|
||||
else:
|
||||
LOG.exception("Erreur de traitement")
|
||||
self.send_json(dict(error="Service temporairement indisponible"), 503)
|
||||
|
||||
def mutation(self):
|
||||
try:
|
||||
origin = self.headers.get("Origin")
|
||||
if self.headers.get("X-Fuel-Request") != "1" or (
|
||||
origin and urllib.parse.urlparse(origin).netloc != self.headers.get("Host")
|
||||
):
|
||||
return self.send_json(dict(error="Requête externe refusée"), 403)
|
||||
content_type = self.headers.get("Content-Type", "").split(";")[0].strip()
|
||||
if content_type and content_type != "application/json":
|
||||
return self.send_json({"error": "Content-Type application/json requis"}, 415)
|
||||
length = int(self.headers.get("Content-Length", 0))
|
||||
if not 0 <= length <= 16384:
|
||||
return self.send_json({"error": "Requête trop volumineuse"}, 413)
|
||||
if length and content_type != "application/json":
|
||||
return self.send_json({"error": "Content-Type application/json requis"}, 415)
|
||||
data = json.loads(self.rfile.read(length)) if length else {}
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Objet JSON attendu")
|
||||
path = urllib.parse.urlparse(self.path).path
|
||||
if path == "/api/advice" and self.command == "POST":
|
||||
return self.send_json(from_payload(data))
|
||||
if path == "/api/collect" and self.command == "POST":
|
||||
result = collector.collect(force=True)
|
||||
return self.send_json(result, 503 if result["status"] == "error" else 200)
|
||||
parts = path.strip("/").split("/")
|
||||
if len(parts) not in (2, 3) or parts[0] != "api" or parts[1] not in ("vehicles", "favorites"):
|
||||
return self.send_json(dict(error="Route introuvable"), 404)
|
||||
entity_id = int(parts[2]) if len(parts) == 3 else None
|
||||
if self.command == "POST" and entity_id is None:
|
||||
result = storage.save_entity(parts[1], data)
|
||||
return self.send_json(result, 201)
|
||||
if self.command == "PUT" and entity_id is not None:
|
||||
return self.send_json(storage.save_entity(parts[1], data, entity_id))
|
||||
if self.command == "DELETE" and entity_id is not None:
|
||||
storage.delete_entity(parts[1], entity_id)
|
||||
return self.send_json(dict(ok=True))
|
||||
return self.send_json(dict(error="Méthode non autorisée"), 405)
|
||||
except Exception as exc:
|
||||
self.handle_error(exc)
|
||||
|
||||
do_POST = mutation
|
||||
do_PUT = mutation
|
||||
do_DELETE = mutation
|
||||
|
||||
|
||||
def main() -> None:
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
ensure_db()
|
||||
server = ThreadingHTTPServer((HOST, PORT), Handler)
|
||||
print(f"Fuel advisor listening on http://{HOST}:{PORT}", flush=True)
|
||||
server.serve_forever()
|
||||
LOG.info("Fuel advisor v2 écoute sur %s:%s", HOST, PORT)
|
||||
ThreadingHTTPServer((HOST, PORT), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user