helloworld / deploy /ingest /headlines.py
eduzrh's picture
Upload deploy/ingest/headlines.py with huggingface_hub
cd67784 verified
Raw History Blame Contribute Delete
5.95 kB
"""全球要闻:抓公开 RSS,输出真实新闻标题。
GDELT 的导出表只有地点没有标题,事件流读起来像地名列表。这里补一路 RSS,
给前端一个"要闻"视图:标题、来源、时间、粗略分类。分类只按关键词打分,
不做地理定位,因此不与地图上的事件点混算。
"""
import html
import json
import os
import re
import sys
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from xml.etree import ElementTree as ET
OUT = "/data/apps/globe/data"
UA = "Mozilla/5.0 (compatible; GeoEvents/1.0)"
FEEDS = [
("NPR", "https://feeds.npr.org/1004/rss.xml"),
("France 24", "https://www.france24.com/en/rss"),
("UN News", "https://news.un.org/feed/subscribe/en/news/all/rss.xml"),
("Moscow Times", "https://www.themoscowtimes.com/rss/news"),
("Sky News", "https://feeds.skynews.com/feeds/rss/world.xml"),
("Global News", "https://globalnews.ca/feed/"),
("WSJ World", "https://feeds.a.dj.com/rss/RSSWorldNews.xml"),
("Anadolu", "https://www.aa.com.tr/en/rss/default?cat=guncel"),
]
CATS = {
"冲突": ["war", "conflict", "attack", "strike", "military", "troop", "missile",
"drone", "killed", "gunmen", "offensive", "ceasefire", "invasion",
"combat", "insurgent", "airstrike", "bomb", "shelling", "frontline"],
"灾害": ["earthquake", "quake", "flood", "wildfire", "hurricane", "typhoon",
"volcano", "landslide", "storm", "tsunami", "evacuat", "rescue"],
"气候": ["climate", "drought", "heatwave", "heat wave", "emission", "warming",
"glacier", "cop2", "cop3", "carbon"],
"外交": ["summit", "diplomat", "sanction", "treaty", "talks", "g7", "g20",
"nato", "security council", "foreign minister", "ambassador"],
"社会": ["protest", "riot", "demonstrat", "migrant", "election", "court",
"police", "strike action", "union", "refugee"],
"经济": ["economy", "inflation", "market", "oil price", "trade", "tariff",
"currency", "stock", "growth", "budget", "debt"],
}
def get(url, timeout=15):
req = urllib.request.Request(url, headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
def strip_tags(s):
s = re.sub(r"<[^>]+>", " ", s or "")
return html.unescape(re.sub(r"\s+", " ", s)).strip()
def parse_date(s):
s = (s or "").strip()
if not s:
return None
try:
return parsedate_to_datetime(s).astimezone(timezone.utc)
except Exception: # noqa: BLE001
pass
for fmt in ("%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%d %H:%M:%S"):
try:
d = datetime.strptime(s, fmt)
return d.replace(tzinfo=timezone.utc) if d.tzinfo is None else d.astimezone(timezone.utc)
except ValueError:
continue
return None
def local_name(tag):
return tag.rsplit("}", 1)[-1].lower()
def items_of(xml_bytes):
"""兼容 RSS 2.0 / RDF / Atom。"""
root = ET.fromstring(xml_bytes)
out = []
for node in root.iter():
if local_name(node.tag) not in ("item", "entry"):
continue
title = link = desc = date = ""
for ch in node:
n = local_name(ch.tag)
if n == "title" and not title:
title = strip_tags(ch.text or "")
elif n == "link" and not link:
link = (ch.get("href") or ch.text or "").strip()
elif n in ("description", "summary") and not desc:
desc = strip_tags(ch.text or "")
elif n in ("pubdate", "published", "updated", "date") and not date:
date = ch.text or ""
if title and link:
out.append({"t": title, "u": link, "d": desc, "dt": parse_date(date)})
return out
SPORT = ("football", "soccer", "basketball", "tennis", "cricket", "olympic",
"la liga", "premier league", "nba", "nfl", "formula 1", "f1 ",
"celebrity", "box office", "album", "film festival")
def categorize(text):
low = text.lower()
best, score = "其他", 0
for cat, words in CATS.items():
s = sum(low.count(w) for w in words)
if s > score:
best, score = cat, s
return best
def main():
now = datetime.now(timezone.utc)
seen, items, errors = set(), [], []
for name, url in FEEDS:
try:
raw = get(url)
got = items_of(raw)
except Exception as e: # noqa: BLE001
errors.append(f"{name}: {type(e).__name__}")
continue
for it in got:
key = re.sub(r"\W+", "", it["t"].lower())[:80]
if not key or key in seen:
continue
seen.add(key)
dt = it["dt"] or now
age = (now - dt).total_seconds() / 3600
if age > 72 or age < -6:
continue
cat = categorize(it["t"] + " " + it["d"])
if cat == "其他" and any(w in (it["t"] + it["d"]).lower() for w in SPORT):
continue
items.append({
"t": it["t"][:220],
"u": it["u"],
"src": name,
"cat": cat,
"ts": int(dt.timestamp()),
"d": (it["d"] or "")[:300],
})
items.sort(key=lambda x: -x["ts"])
items = items[:140]
os.makedirs(OUT, exist_ok=True)
payload = {"generated": now.strftime("%Y-%m-%dT%H:%M:%SZ"), "items": items}
with open(os.path.join(OUT, "headlines.json"), "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False)
counts = {}
for it in items:
counts[it["cat"]] = counts.get(it["cat"], 0) + 1
print(json.dumps({"headlines": len(items), "by_cat": counts, "errors": errors},
ensure_ascii=False))
if __name__ == "__main__":
main()