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.
406 lines
14 KiB
Python
406 lines
14 KiB
Python
"""Actualités géopolitiques et logistiques : détection de nouveaux articles, extraction structurée.
|
||
|
||
Le programme récupère lui-même les articles (RSS Google News, GDELT en secours), ne relance
|
||
l'extraction Ollama que pour un **nouvel** article jamais analysé, et exige une source.
|
||
Aucune règle n'est inventée : un article sans URL ou sans date n'est pas transformé en signal.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import html
|
||
import json
|
||
import os
|
||
import re
|
||
import time
|
||
import unicodedata
|
||
import urllib.parse
|
||
import urllib.request
|
||
from datetime import date, datetime, timedelta, timezone
|
||
from xml.etree import ElementTree as ET
|
||
|
||
import llm
|
||
import storage
|
||
import upstream
|
||
|
||
USER_AGENT = upstream.USER_AGENT
|
||
MAX_ARTICLES_PER_RUN = int(os.environ.get("FUEL_NEWS_MAX_PER_RUN", "8"))
|
||
# 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"],
|
||
"suez_babelmandeb": ["Bab el-Mandeb Suez pétrole", "mer Rouge pétrolier attaque"],
|
||
"opep": ["OPEP+ décision production pétrole", "OPEC+ quota oil output"],
|
||
"sanctions": ["sanctions pétrole Russie Iran", "oil sanctions export"],
|
||
"raffineries": ["raffinerie arrêt incident", "refinery outage fire"],
|
||
"depots_greves": ["grève dépôt carburant", "blocage raffinerie France carburant"],
|
||
"fiscalite": ["taxe carburant accise France", "fiscalité carburant augmentation"],
|
||
}
|
||
|
||
PROMPT = """Tu analyses un article de presse pour un outil interne d'analyse des prix des carburants.
|
||
Réponds UNIQUEMENT par un objet JSON, sans texte autour, au format :
|
||
{{"pertinent": true|false, "evenements": [{{"type": "chokepoint|offre|raffinage|logistique|sanctions|fiscalite|autre",
|
||
"direction": "hausse|baisse|incertaine", "magnitude": "faible|moyenne|forte|inconnue",
|
||
"carburants": ["gazole","sp95","e10","sp98","e85","gplc"] ou [], "zone": "lieu ou région en clair",
|
||
"horizon_jours": entier ou null, "confiance": nombre entre 0 et 1,
|
||
"debut": "AAAA-MM-JJ" ou null, "fin": "AAAA-MM-JJ" ou null}}]}}
|
||
Règles strictes : n'invente rien. Si l'article ne concerne pas l'approvisionnement, la logistique,
|
||
la production, les sanctions ou la fiscalité des carburants, mets "pertinent": false et une liste vide.
|
||
La direction décrit l'effet probable sur les prix, "incertaine" si ce n'est pas clair.
|
||
horizon_jours est la durée estimée de l'effet en jours, null si inconnue. Ne dépasse jamais 60.
|
||
|
||
Titre : {title}
|
||
Source : {source}
|
||
Date de publication : {published}
|
||
Texte : {text}
|
||
"""
|
||
|
||
|
||
def 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]
|
||
|
||
|
||
def strip_html(text):
|
||
text = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", text or "", flags=re.S | re.I)
|
||
text = re.sub(r"<[^>]+>", " ", text)
|
||
return re.sub(r"\s+", " ", html.unescape(text)).strip()
|
||
|
||
|
||
def parse_rss(xml, source_label, topic):
|
||
"""Articles d'un flux RSS, avec date de publication quand elle est fournie."""
|
||
articles = []
|
||
try:
|
||
root = ET.fromstring(xml)
|
||
except ET.ParseError:
|
||
return articles
|
||
for item in root.findall(".//item"):
|
||
link = (item.findtext("link") or "").strip()
|
||
title = strip_html(item.findtext("title") or "")
|
||
if not link or not title:
|
||
continue
|
||
published = parse_rss_date(item.findtext("pubDate") or "")
|
||
articles.append(
|
||
dict(
|
||
hash=article_hash(link),
|
||
url=link,
|
||
title=title[:300],
|
||
source=strip_html(item.findtext("source") or source_label)[:80],
|
||
topic=topic,
|
||
published_at=published,
|
||
observed_at=published,
|
||
summary=strip_html(item.findtext("description") or "")[:600],
|
||
)
|
||
)
|
||
return articles
|
||
|
||
|
||
def parse_rss_date(text):
|
||
for pattern in ("%a, %d %b %Y %H:%M:%S %z", "%a, %d %b %Y %H:%M:%S %Z", "%Y-%m-%dT%H:%M:%SZ"):
|
||
try:
|
||
return datetime.strptime(text.strip(), pattern).astimezone(timezone.utc).date().isoformat()
|
||
except (ValueError, AttributeError):
|
||
continue
|
||
return None
|
||
|
||
|
||
def google_news(query, topic, timeout=20):
|
||
url = "https://news.google.com/rss/search?q=" + urllib.parse.quote(query) + "&hl=fr&gl=FR&ceid=FR:fr"
|
||
return parse_rss(upstream.fetch_bytes(url, timeout, 4_000_000), "Google News", topic)
|
||
|
||
|
||
def gdelt(query, topic, timeout=30):
|
||
"""Secours : GDELT répond de façon intermittente (429 tolérés)."""
|
||
url = (
|
||
"https://api.gdeltproject.org/api/v2/doc/doc?query="
|
||
+ urllib.parse.quote(query)
|
||
+ "&mode=artlist&maxrecords=10&format=json&sort=datedesc"
|
||
)
|
||
payload = upstream.fetch_bytes(url, timeout, 2_000_000)
|
||
try:
|
||
rows = json.loads(payload).get("articles", [])
|
||
except (ValueError, AttributeError):
|
||
return []
|
||
articles = []
|
||
for row in rows:
|
||
link, title = str(row.get("url") or "").strip(), strip_html(str(row.get("title") or ""))
|
||
if not link or not title:
|
||
continue
|
||
day = None
|
||
stamp = str(row.get("seendate") or "")
|
||
if len(stamp) >= 8 and stamp[:8].isdigit():
|
||
day = f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]}"
|
||
articles.append(
|
||
dict(
|
||
hash=article_hash(link),
|
||
url=link,
|
||
title=title[:300],
|
||
source=str(row.get("domain") or "GDELT")[:80],
|
||
topic=topic,
|
||
published_at=day,
|
||
observed_at=day,
|
||
summary="",
|
||
)
|
||
)
|
||
return articles
|
||
|
||
|
||
def gather(topic_queries=None, use_gdelt=True):
|
||
"""Récupère les articles de tous les sujets ; lève si aucune source ne répond."""
|
||
topic_queries = topic_queries or TOPICS
|
||
articles, errors = [], []
|
||
for topic, queries in topic_queries.items():
|
||
for query in queries:
|
||
try:
|
||
articles.extend(google_news(query, topic))
|
||
except Exception as exc:
|
||
errors.append(f"rss {topic}: {type(exc).__name__}")
|
||
if use_gdelt:
|
||
try:
|
||
articles.extend(gdelt(queries[0], topic))
|
||
except Exception as exc:
|
||
errors.append(f"gdelt {topic}: {type(exc).__name__}")
|
||
if not articles and errors:
|
||
raise RuntimeError("aucune source d’actualités joignable (" + ", ".join(errors[:4]) + ")")
|
||
unique = {article["hash"]: article for article in articles}
|
||
return list(unique.values()), errors
|
||
|
||
|
||
def analyse(article, topic, models=None):
|
||
"""Extraction Ollama : renvoie la liste d'événements structurés, jamais une décision."""
|
||
prompt = PROMPT.format(
|
||
title=article["title"],
|
||
source=article.get("source", ""),
|
||
published=article.get("published_at") or "inconnue",
|
||
text=(article.get("summary") or article["title"])[:2500],
|
||
)
|
||
data, model = llm.extract(prompt, models=models)
|
||
if not data.get("pertinent"):
|
||
return [], model
|
||
observed = article.get("published_at") or article.get("observed_at")
|
||
events = []
|
||
for raw in (data.get("evenements") or [])[:5]:
|
||
if not isinstance(raw, dict):
|
||
continue
|
||
direction = str(raw.get("direction") or "incertaine").lower()
|
||
if direction not in ("hausse", "baisse", "incertaine"):
|
||
direction = "incertaine"
|
||
horizon = raw.get("horizon_jours")
|
||
try:
|
||
horizon = max(0, min(60, int(horizon))) if horizon is not None else None
|
||
except (TypeError, ValueError):
|
||
horizon = None
|
||
try:
|
||
confidence = max(0.0, min(1.0, float(raw.get("confiance"))))
|
||
except (TypeError, ValueError):
|
||
confidence = None
|
||
end = raw.get("fin")
|
||
if not end and observed and horizon:
|
||
end = (date.fromisoformat(observed) + timedelta(days=horizon)).isoformat()
|
||
events.append(
|
||
dict(
|
||
url_hash=article["hash"],
|
||
topic=topic,
|
||
event_type=str(raw.get("type") or "autre")[:40],
|
||
direction=direction,
|
||
magnitude=str(raw.get("magnitude") or "inconnue")[:20],
|
||
fuels=[str(f)[:10] for f in (raw.get("carburants") or []) if isinstance(f, (str, int))][:6],
|
||
zone=str(raw.get("zone") or "")[:80],
|
||
horizon_days=horizon,
|
||
confidence=confidence,
|
||
valid_from=raw.get("debut") or observed,
|
||
valid_until=end,
|
||
observed_at=observed,
|
||
published_at=article.get("published_at"),
|
||
source_url=article["url"],
|
||
extracted_by=model,
|
||
)
|
||
)
|
||
return events, model
|
||
|
||
|
||
def collect(topic_queries=None, models=None, force=False, limit=None):
|
||
"""Contrôle les actualités, 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 = keep[:limit]
|
||
events, analysed, durations = 0, [], []
|
||
for article in todo:
|
||
started = time.monotonic()
|
||
try:
|
||
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=detail,
|
||
)
|