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.
247 lines
9.7 KiB
Python
247 lines
9.7 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 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", "3"))
|
||
|
||
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 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 et n'appelle Ollama que sur des articles jamais analysés."""
|
||
articles, errors = gather(topic_queries)
|
||
fresh = storage.save_articles(articles, "geo")
|
||
limit = limit or MAX_ARTICLES_PER_RUN
|
||
todo = [article for article in fresh if article.get("topic")][:limit]
|
||
events, analysed = 0, []
|
||
for article in todo:
|
||
try:
|
||
found, _model = analyse(article, article["topic"], models=models)
|
||
except Exception as exc:
|
||
errors.append(f"ollama {article['hash'][:6]}: {type(exc).__name__}")
|
||
continue
|
||
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 [""])
|
||
return dict(
|
||
status="ok" if articles else "error",
|
||
articles=len(articles),
|
||
new=len(todo),
|
||
analysed=len(analysed),
|
||
events=events,
|
||
errors=errors[:6],
|
||
last_observation_at=newest or None,
|
||
detail="; ".join(errors[:3]) if errors else f"{len(analysed)} article(s) analysé(s)",
|
||
)
|