Ordonnanceur multi-frequences, supervision, promotions et metadonnees temporelles
Chaque source a sa cadence et sa fenetre (prix locaux horaires 24/7, BCE jours ouvres apres 16h15, bulletin UE le jeudi, DGEC mensuel avec detection de nouvelle periode, PortWatch quotidien avec fenetre glissante pour les revisions, actualites toutes les 2 heures, promotions 3 fois par jour). Supervision persistante (table jobs) exposee par /api/jobs et une fenetre dediee. Evenements prix uniquement en cas de changement de prix ou d horodatage declare, actualisation forcee du flux local au-dela de 15 minutes lors d un conseil. Extraction Ollama (mistral-small3.2:24b) des actualites geopolitiques et des operations commerciales, sans jamais decider du conseil, avec observed_at, published_at, fetched_at, valid_from et valid_until distincts.
This commit is contained in:
185
promotions.py
Normal file
185
promotions.py
Normal file
@@ -0,0 +1,185 @@
|
||||
"""Opérations commerciales carburant : recherche multi-sources et extraction structurée.
|
||||
|
||||
Les annonces sont récupérées par le programme (actualités et pages publiques des enseignes),
|
||||
puis structurées par Ollama. Une annonce sans source vérifiable n'est jamais enregistrée.
|
||||
« Prix coûtant » n'implique pas « moins cher » : la comparaison avec les autres stations
|
||||
est faite séparément, par le moteur de décision.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import llm
|
||||
import news
|
||||
import storage
|
||||
|
||||
MAX_ITEMS_PER_BRAND = int(os.environ.get("FUEL_PROMO_MAX_PER_BRAND", "4"))
|
||||
|
||||
BRANDS = (
|
||||
"E.Leclerc",
|
||||
"Carrefour",
|
||||
"Intermarché",
|
||||
"Auchan",
|
||||
"Système U",
|
||||
"Cora",
|
||||
"TotalEnergies",
|
||||
"Esso",
|
||||
"BP",
|
||||
"Avia",
|
||||
"Netto",
|
||||
)
|
||||
|
||||
BRAND_QUERIES = {
|
||||
"E.Leclerc": ["E.Leclerc carburant prix coûtant", "Leclerc essence opération carburant"],
|
||||
"Carrefour": ["Carrefour carburant prix coûtant", "Carrefour essence remise carburant"],
|
||||
"Intermarché": ["Intermarché carburant prix coûtant", "Intermarché essence opération"],
|
||||
"Auchan": ["Auchan carburant prix coûtant", "Auchan essence opération carburant"],
|
||||
"Système U": ["Système U carburant prix coûtant", "U express essence remise"],
|
||||
"Cora": ["Cora carburant prix coûtant"],
|
||||
"TotalEnergies": ["TotalEnergies remise carburant", "TotalEnergies prix carburant opération"],
|
||||
"Esso": ["Esso remise carburant"],
|
||||
"BP": ["BP remise carburant"],
|
||||
"Avia": ["Avia remise carburant"],
|
||||
"Netto": ["Netto carburant prix coûtant"],
|
||||
}
|
||||
|
||||
GENERIC_QUERIES = [
|
||||
"prix coûtant carburant week-end",
|
||||
"prix plafonné carburant",
|
||||
"remise carburant",
|
||||
"bon d’achat carburant hypermarché",
|
||||
"opération carburant à prix coûtant",
|
||||
]
|
||||
|
||||
NATURES = ("prix_coutant", "prix_plafonne", "remise_litre", "bon_achat", "carte_fidelite", "autre")
|
||||
|
||||
PROMPT = """Tu extrais des opérations commerciales sur les carburants depuis un texte de presse.
|
||||
Réponds UNIQUEMENT par un objet JSON :
|
||||
{{"operations": [{{"enseigne": "nom de l'enseigne", "nature": "prix_coutant|prix_plafonne|remise_litre|bon_achat|carte_fidelite|autre",
|
||||
"remise_par_litre": nombre en euros ou null, "carburants": ["gazole","sp95","e10","sp98","e85","gplc"] ou [],
|
||||
"zone": "zone ou liste de stations en clair ou vide", "debut": "AAAA-MM-JJ" ou null, "fin": "AAAA-MM-JJ" ou null,
|
||||
"confiance": nombre entre 0 et 1}}]}}
|
||||
Règles : n'invente aucune enseigne absente du texte, aucune date absente, aucun montant absent.
|
||||
Si le texte ne décrit pas d'opération carburant en cours ou annoncée, renvoie une liste vide.
|
||||
La confiance reflète la précision du texte (dates et périmètre explicites = élevée).
|
||||
|
||||
Titre : {title}
|
||||
Source : {source}
|
||||
Date : {published}
|
||||
Texte : {text}
|
||||
"""
|
||||
|
||||
|
||||
def gather(use_gdelt=True):
|
||||
"""Récupère les articles liés aux opérations commerciales de chaque enseigne."""
|
||||
queries = {brand: BRAND_QUERIES.get(brand, [f"{brand} carburant"]) for brand in BRANDS}
|
||||
queries["_general"] = GENERIC_QUERIES
|
||||
articles, errors = news.gather(queries, use_gdelt=use_gdelt)
|
||||
return articles, errors
|
||||
|
||||
|
||||
def analyse(article, models=None):
|
||||
"""Extraction structurée d'une annonce : enseigne, nature, dates, périmètre, confiance."""
|
||||
prompt = PROMPT.format(
|
||||
title=article["title"],
|
||||
source=article.get("source", ""),
|
||||
published=article.get("published_at") or "inconnue",
|
||||
text=(article.get("summary") or article["title"])[:2500],
|
||||
)
|
||||
data, model = llm.extract(prompt, models=models)
|
||||
observed = article.get("published_at") or article.get("observed_at")
|
||||
out = []
|
||||
for raw in (data.get("operations") or [])[:4]:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
brand = str(raw.get("enseigne") or "").strip()[:60]
|
||||
nature = str(raw.get("nature") or "autre").strip().lower()
|
||||
if not brand or nature not in NATURES:
|
||||
continue
|
||||
if (
|
||||
brand.lower() not in article["title"].lower()
|
||||
and brand.lower() not in (article.get("summary") or "").lower()
|
||||
):
|
||||
# Défense simple contre une enseigne inventée par le modèle.
|
||||
continue
|
||||
discount = raw.get("remise_par_litre")
|
||||
try:
|
||||
discount = round(float(discount), 3) if discount is not None else None
|
||||
except (TypeError, ValueError):
|
||||
discount = None
|
||||
try:
|
||||
confidence = max(0.0, min(1.0, float(raw.get("confiance"))))
|
||||
except (TypeError, ValueError):
|
||||
confidence = None
|
||||
valid_from = raw.get("debut") or observed
|
||||
out.append(
|
||||
dict(
|
||||
brand=brand,
|
||||
nature=nature,
|
||||
discount_per_liter=discount,
|
||||
fuels=[str(f)[:10] for f in (raw.get("carburants") or []) if isinstance(f, (str, int))][:6],
|
||||
scope=article.get("topic") or "",
|
||||
stations=str(raw.get("zone") or "")[:200],
|
||||
valid_from=valid_from,
|
||||
valid_until=raw.get("fin"),
|
||||
observed_at=observed,
|
||||
published_at=article.get("published_at"),
|
||||
source_url=article["url"],
|
||||
confidence=confidence,
|
||||
extracted_by=model,
|
||||
raw_excerpt=(article.get("summary") or article["title"])[:400],
|
||||
)
|
||||
)
|
||||
return out, model
|
||||
|
||||
|
||||
MAX_ARTICLES_PER_RUN = int(os.environ.get("FUEL_PROMO_MAX_PER_RUN", "3"))
|
||||
|
||||
|
||||
def collect(models=None, force=False, limit=None):
|
||||
"""Recherche les opérations, n'analyse que les nouveaux articles, enregistre les annonces.
|
||||
|
||||
Chaque extraction prend environ 2 à 3 minutes avec mistral-small3.2:24b : le nombre
|
||||
d'articles par passage reste volontairement bas pour que le passage reste borné.
|
||||
"""
|
||||
articles, errors = gather()
|
||||
fresh = storage.save_articles(articles, "promotions")
|
||||
todo = [article for article in fresh if article.get("topic")][: limit or MAX_ARTICLES_PER_RUN]
|
||||
saved, analysed = 0, []
|
||||
for article in todo:
|
||||
try:
|
||||
found, _model = analyse(article, models=models)
|
||||
except Exception as exc:
|
||||
errors.append(f"ollama {article['hash'][:6]}: {type(exc).__name__}")
|
||||
continue
|
||||
if found:
|
||||
saved += storage.save_promotions(found)
|
||||
analysed.append(article["hash"])
|
||||
storage.mark_analysed(analysed)
|
||||
newest = max([article.get("published_at") or "" for article in articles] or [""])
|
||||
return dict(
|
||||
status="ok" if articles else "error",
|
||||
articles=len(articles),
|
||||
new=len(todo),
|
||||
analysed=len(analysed),
|
||||
promotions=saved,
|
||||
errors=errors[:6],
|
||||
last_observation_at=newest or None,
|
||||
detail="; ".join(errors[:3]) if errors else f"{saved} opération(s) enregistrée(s)",
|
||||
)
|
||||
|
||||
|
||||
def active(today=None):
|
||||
"""Opérations en cours ou à venir, avec leur source — pour l'affichage et le conseil."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
today = today or datetime.now(timezone.utc).date()
|
||||
out = []
|
||||
for row in storage.promotions(today=today):
|
||||
if row.get("valid_from") and row["valid_from"] > today.isoformat():
|
||||
state = "annoncée"
|
||||
else:
|
||||
state = "en cours"
|
||||
out.append(dict(row, state=state))
|
||||
return out
|
||||
Reference in New Issue
Block a user