Chaque facteur distingue desormais la donnee observee et son effet suppose sur les prix, avec fleche justifiee, ecarts chiffres a J-1, J-7, a la publication precedente et a la moyenne 30 jours. Les inversions de signe sont verrouillees par tests : un euro plus fort face au dollar est baissier, une baisse du trafic de petroliers est haussiere. La mesure PortWatch d Ormuz, tombant a 0-2 petroliers par jour, est declared non exploitable plutot que transformee en signal. Les durees OSRM sont etiquetees hors trafic et le cache separe la distance statique (90 jours) de l ETA de trafic (15 minutes, Google TRAFFIC_AWARE uniquement) : une ancienne ETA n est jamais presentee comme actuelle. Le cache de routes normalise l origine a environ 100 m et la rattache au favori quand la position mesuree lui correspond. Benchmark etiquete Gemma 12B contre Mistral 24B : le 24b reste primaire (rappel et JSON), le 12b en repli.
267 lines
9.8 KiB
Python
267 lines
9.8 KiB
Python
"""Opérations commerciales carburant : recherche multi-sources et extraction structurée.
|
||
|
||
Les annonces sont récupérées par le programme (actualités et pages publiques des enseignes),
|
||
puis structurées par Ollama. Une annonce sans source vérifiable n'est jamais enregistrée.
|
||
« Prix coûtant » n'implique pas « moins cher » : la comparaison avec les autres stations
|
||
est faite séparément, par le moteur de décision.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import time
|
||
|
||
import llm
|
||
import news
|
||
import storage
|
||
|
||
MAX_ITEMS_PER_BRAND = int(os.environ.get("FUEL_PROMO_MAX_PER_BRAND", "4"))
|
||
|
||
BRANDS = (
|
||
"E.Leclerc",
|
||
"Carrefour",
|
||
"Intermarché",
|
||
"Auchan",
|
||
"Système U",
|
||
"Cora",
|
||
"TotalEnergies",
|
||
"Esso",
|
||
"BP",
|
||
"Avia",
|
||
"Netto",
|
||
)
|
||
|
||
BRAND_QUERIES = {
|
||
"E.Leclerc": ["E.Leclerc carburant prix coûtant", "Leclerc essence opération carburant"],
|
||
"Carrefour": ["Carrefour carburant prix coûtant", "Carrefour essence remise carburant"],
|
||
"Intermarché": ["Intermarché carburant prix coûtant", "Intermarché essence opération"],
|
||
"Auchan": ["Auchan carburant prix coûtant", "Auchan essence opération carburant"],
|
||
"Système U": ["Système U carburant prix coûtant", "U express essence remise"],
|
||
"Cora": ["Cora carburant prix coûtant"],
|
||
"TotalEnergies": ["TotalEnergies remise carburant", "TotalEnergies prix carburant opération"],
|
||
"Esso": ["Esso remise carburant"],
|
||
"BP": ["BP remise carburant"],
|
||
"Avia": ["Avia remise carburant"],
|
||
"Netto": ["Netto carburant prix coûtant"],
|
||
}
|
||
|
||
GENERIC_QUERIES = [
|
||
"prix coûtant carburant week-end",
|
||
"prix plafonné carburant",
|
||
"remise carburant",
|
||
"bon d’achat carburant hypermarché",
|
||
"opération carburant à prix coûtant",
|
||
]
|
||
|
||
NATURES = ("prix_coutant", "prix_plafonne", "remise_litre", "bon_achat", "carte_fidelite", "autre")
|
||
|
||
PROMPT = """Tu extrais des opérations commerciales sur les carburants depuis un texte de presse.
|
||
Réponds UNIQUEMENT par un objet JSON :
|
||
{{"operations": [{{"enseigne": "nom de l'enseigne", "nature": "prix_coutant|prix_plafonne|remise_litre|bon_achat|carte_fidelite|autre",
|
||
"remise_par_litre": nombre en euros ou null, "carburants": ["gazole","sp95","e10","sp98","e85","gplc"] ou [],
|
||
"zone": "zone ou liste de stations en clair ou vide", "debut": "AAAA-MM-JJ" ou null, "fin": "AAAA-MM-JJ" ou null,
|
||
"confiance": nombre entre 0 et 1}}]}}
|
||
Règles : n'invente aucune enseigne absente du texte, aucune date absente, aucun montant absent.
|
||
Si le texte ne décrit pas d'opération carburant en cours ou annoncée, renvoie une liste vide.
|
||
La confiance reflète la précision du texte (dates et périmètre explicites = élevée).
|
||
|
||
Titre : {title}
|
||
Source : {source}
|
||
Date : {published}
|
||
Texte : {text}
|
||
"""
|
||
|
||
|
||
def gather(use_gdelt=True):
|
||
"""Récupère les articles liés aux opérations commerciales de chaque enseigne."""
|
||
queries = {brand: BRAND_QUERIES.get(brand, [f"{brand} carburant"]) for brand in BRANDS}
|
||
queries["_general"] = GENERIC_QUERIES
|
||
articles, errors = news.gather(queries, use_gdelt=use_gdelt)
|
||
return articles, errors
|
||
|
||
|
||
def analyse(article, models=None):
|
||
"""Extraction structurée d'une annonce : enseigne, nature, dates, périmètre, confiance."""
|
||
prompt = PROMPT.format(
|
||
title=article["title"],
|
||
source=article.get("source", ""),
|
||
published=article.get("published_at") or "inconnue",
|
||
text=(article.get("summary") or article["title"])[:2500],
|
||
)
|
||
data, model = llm.extract(prompt, models=models)
|
||
observed = article.get("published_at") or article.get("observed_at")
|
||
out = []
|
||
for raw in (data.get("operations") or [])[:4]:
|
||
if not isinstance(raw, dict):
|
||
continue
|
||
brand = str(raw.get("enseigne") or "").strip()[:60]
|
||
nature = str(raw.get("nature") or "autre").strip().lower()
|
||
if not brand or nature not in NATURES:
|
||
continue
|
||
if (
|
||
brand.lower() not in article["title"].lower()
|
||
and brand.lower() not in (article.get("summary") or "").lower()
|
||
):
|
||
# Défense simple contre une enseigne inventée par le modèle.
|
||
continue
|
||
discount = raw.get("remise_par_litre")
|
||
try:
|
||
discount = round(float(discount), 3) if discount is not None else None
|
||
except (TypeError, ValueError):
|
||
discount = None
|
||
try:
|
||
confidence = max(0.0, min(1.0, float(raw.get("confiance"))))
|
||
except (TypeError, ValueError):
|
||
confidence = None
|
||
valid_from = raw.get("debut") or observed
|
||
out.append(
|
||
dict(
|
||
brand=brand,
|
||
nature=nature,
|
||
discount_per_liter=discount,
|
||
fuels=[str(f)[:10] for f in (raw.get("carburants") or []) if isinstance(f, (str, int))][:6],
|
||
scope=article.get("topic") or "",
|
||
stations=str(raw.get("zone") or "")[:200],
|
||
valid_from=valid_from,
|
||
valid_until=raw.get("fin"),
|
||
observed_at=observed,
|
||
published_at=article.get("published_at"),
|
||
source_url=article["url"],
|
||
confidence=confidence,
|
||
extracted_by=model,
|
||
raw_excerpt=(article.get("summary") or article["title"])[:400],
|
||
)
|
||
)
|
||
return out, model
|
||
|
||
|
||
MAX_ARTICLES_PER_RUN = int(os.environ.get("FUEL_PROMO_MAX_PER_RUN", "8"))
|
||
|
||
|
||
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.
|
||
|
||
Chaque extraction prend environ 2 à 3 minutes avec mistral-small3.2:24b : le nombre
|
||
d'articles par passage reste volontairement bas pour que le passage reste borné.
|
||
"""
|
||
articles, errors = gather()
|
||
fresh = storage.save_articles(articles, "promotions")
|
||
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)
|
||
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=detail,
|
||
)
|
||
|
||
|
||
def active(today=None):
|
||
"""Opérations en cours ou à venir, avec leur source — pour l'affichage et le conseil."""
|
||
from datetime import datetime, timezone
|
||
|
||
today = today or datetime.now(timezone.utc).date()
|
||
out = []
|
||
for row in storage.promotions(today=today):
|
||
if row.get("valid_from") and row["valid_from"] > today.isoformat():
|
||
state = "annoncée"
|
||
else:
|
||
state = "en cours"
|
||
out.append(dict(row, state=state))
|
||
return out
|