feat(market): 准入 10 项技能,补齐 AI 日报与高德完整安装包 (#350)

- 准入 10 项 installable 技能:agent-reach、dingtalk-api、follow-builders、humanizer-zh、karpathy-guidelines、marketingskills、netease-skills、wecom-cli(原 pin 不变),以及完整 MIT 本地版 ai-news-radar(LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319)和 ClawHub 1.1.1 完整 ZIP 的 amap-jsapi-skill(sha256 9468743ee18dbe1704e8a98f47f6628d6a4e6acec30a05f0b8f59a07603d011f)。
- 瑞幸、MiniMax 图片/语音、LumaRescue、美团跑腿、Ian 小黑、女娲 继续 listing-only。
- 高德许可按 SKILL.md 的 MIT 声明保守记录,skill-card/ClawHub 写 MIT-0 的差异已在 ADMISSION.md 披露。
- validate、translate 通过;CodeQL 对上游原样 update_news.py 的 5 条告警经 mashagua 确认忽略。
This commit is contained in:
mashagua authored and GitHub committed 2026-11-24 17:11:50 +08:00
1 parent 8006ad8518
commit 91563b4695
62 files changed
+23030 -98

No files matched your search

+1
View File
@@ -0,0 +1 @@
# Package marker for tests.
@@ -0,0 +1,433 @@
#!/usr/bin/env python3
"""Explainable AI relevance scoring for news records."""
from __future__ import annotations
import re
from typing import Any
from urllib.parse import urlparse
AI_KEYWORDS = [
"a.i.",
"agent view",
"agent skills",
"for agents",
"parallel agent",
"并行 agent",
"known agents",
"hermes-agent",
"agentmemory",
"aigc",
"llm",
"gpt",
"claude",
"gemini",
"deepseek",
"openai",
"anthropic",
"grok",
"copilot",
"codex",
"mcp",
"hugging face",
"huggingface",
"transformer",
"prompt",
"diffusion",
"多模态",
"交互模型",
"变换器",
"语言模型",
"视觉语言模型",
"基础模型",
"本地模型",
"具身智能",
"大模型",
"人工智能",
"机器学习",
"深度学习",
"智能体",
"算力",
"推理",
"微调",
]
TECH_KEYWORDS = [
"robot",
"robotics",
"embodied",
"autonomous",
"vision",
"chip",
"semiconductor",
"cuda",
"npu",
"gpu",
"cloud",
"developer",
"benchmark",
"dataset",
"eval",
"evaluation",
"sandbox",
"context",
"开源",
"技术",
"编程",
"软件",
"沙箱",
"上下文",
"芯片",
"机器人",
"具身",
]
NOISE_KEYWORDS = [
"娱乐",
"明星",
"八卦",
"足球",
"篮球",
"彩票",
"情感",
"旅游",
"美食",
]
COMMERCE_NOISE_KEYWORDS = [
"淘宝",
"天猫",
"京东",
"拼多多",
"券后",
"热销总榜",
"促销",
"优惠",
"补贴",
"下单",
"首发价",
]
UNSAFE_HARD_PATTERNS = [
re.compile(r"\bcreampie\b", re.I),
re.compile(r"\bblowjob\b", re.I),
re.compile(r"\bsuck (?:your|my) (?:dick|cock)\b", re.I),
re.compile(r"中出|婊子|吸你的鸡鸡|操虚拟女友", re.I),
]
UNSAFE_PROMO_PATTERNS = [
re.compile(r"\b(?:nsfw|nudes?|porn(?:ography)?)\b", re.I),
re.compile(r"\buncensored pictures?\b", re.I),
re.compile(r"\bvirtual girlfriends?\b", re.I),
re.compile(r"\bknock her up\b", re.I),
re.compile(r"未经审查的图片|虚拟女友|色情内容|成人内容", re.I),
]
EN_SIGNAL_RE = re.compile(
r"(?i)(?<![a-z0-9])(ai|aigc|llm|gpt|openai|anthropic|deepseek|gemini|claude|grok|xai|robot|robotics|embodied|autonomous|machine learning|artificial intelligence|transformer|diffusion|agent)(?![a-z0-9])"
)
MEANINGFUL_EN_SIGNAL_RE = re.compile(
r"(?i)(?<![a-z0-9])(ai|aigc|llm|gpt|openai|anthropic|deepseek|gemini|claude|grok|xai|robot|robotics|embodied|autonomous|machine learning|artificial intelligence|transformer|diffusion)(?![a-z0-9])"
)
# "cursor" needs its own word-boundary regex rather than living in the plain
# substring-matched AI_KEYWORDS list: "cursor" is a substring of ordinary
# words like "precursor" (e.g. Cloudflare's "Precursor" product announcement),
# which was scoring 0.65/AI-related purely off that false substring match.
CURSOR_SIGNAL_RE = re.compile(r"(?i)(?<![a-z0-9])cursor(?![a-z0-9])")
BROAD_AI_TERMS = {"agent", "模型", "推理"}
AI_RELEVANCE_THRESHOLD = 0.65
AI_BROAD_RELEVANCE_FLOOR = 0.3
SOURCE_PRIORS = {
"official_ai": 0.35,
"curated_media": 0.18,
"aibase": 0.45,
"aihot": 0.45,
"aihubtoday": 0.45,
"followbuilders": 0.25,
"opmlrss": 0.15,
"xapi": 0.15,
"socialdata_x": 0.15,
}
AI_DEFAULT_SOURCES = {"aibase", "aihot", "aihubtoday"}
CURATED_MEDIA_TRUSTED_SOURCE_KEYWORDS = [
"the decoder ai news",
"techcrunch ai",
"venturebeat ai",
"artificial intelligence news",
"claude code releases",
]
CURATED_MEDIA_RESEARCH_SOURCE_KEYWORDS = [
"marktechpost research",
]
CURATED_MEDIA_RESEARCH_TERMS = [
"paper",
"arxiv",
"research",
"benchmark",
"bench",
"eval",
"evaluation",
"dataset",
"model",
"llm",
"agent",
"diffusion",
"transformer",
"multimodal",
"reasoning",
"inference",
"training",
"open-source",
"robot",
"governance",
]
CURATED_MEDIA_BUSINESS_TERMS = [
"funding",
"raises",
"raised",
"startup",
"acquire",
"acquisition",
"merger",
"revenue",
"enterprise",
"ipo",
"valuation",
]
LABEL_KEYWORDS = [
("model_release", ["model", "gpt", "claude", "gemini", "deepseek", "llm", "模型", "大模型", "发布", "release"]),
("developer_tool", ["copilot", "codex", "mcp", "api", "sdk", "developer", "开发者", "编程", "代码", "coding"]),
("agent_workflow", ["agent", "智能体", "workflow", "工作流", "tool use", "function calling"]),
("research_paper", ["paper", "arxiv", "research", "benchmark", "eval", "论文", "研究", "评测", "榜单"]),
("infra_compute", ["gpu", "npu", "cuda", "chip", "semiconductor", "算力", "芯片", "推理"]),
("robotics", ["robot", "robotics", "embodied", "机器人", "具身"]),
("industry_business", ["funding", "acquire", "融资", "收购", "估值", "营收", "公司"]),
("ai_product_update", ["openai", "anthropic", "google", "perplexity", "cursor", "产品", "上线", "更新"]),
]
def contains_any_keyword(haystack: str, keywords: list[str]) -> bool:
h = haystack.lower()
return any(k in h for k in keywords)
def contains_unsafe_promotional_content(text: str) -> bool:
"""Block explicit adult promotion without hiding a single policy/news mention."""
if any(pattern.search(text) for pattern in UNSAFE_HARD_PATTERNS):
return True
return sum(bool(pattern.search(text)) for pattern in UNSAFE_PROMO_PATTERNS) >= 2
def matched_keywords(haystack: str, keywords: list[str]) -> list[str]:
h = haystack.lower()
return sorted({k for k in keywords if k in h})
def contains_meaningful_ai_signal(haystack: str) -> bool:
h = haystack.lower()
if MEANINGFUL_EN_SIGNAL_RE.search(h):
return True
if CURSOR_SIGNAL_RE.search(h):
return True
return any(k in h for k in AI_KEYWORDS if k not in BROAD_AI_TERMS)
def _label_for_text(text: str, has_tech: bool) -> str:
for label, keywords in LABEL_KEYWORDS:
if contains_any_keyword(text, keywords):
return label
if has_tech:
return "ai_tech"
return "ai_general"
def _result(
*,
is_ai_related: bool,
score: float,
label: str,
reason: str,
signals: list[str] | None = None,
noise: list[str] | None = None,
) -> dict[str, Any]:
return {
"is_ai_related": bool(is_ai_related),
"score": round(max(0.0, min(1.0, score)), 2),
"label": label,
"reason": reason,
"signals": signals or [],
"noise": noise or [],
}
def score_ai_relevance(record: dict[str, Any]) -> dict[str, Any]:
"""Return an explainable relevance score while preserving the old keep/drop behavior."""
site_id = str(record.get("site_id") or "")
title = str(record.get("title") or "")
source = str(record.get("source") or "")
site_name = str(record.get("site_name") or "")
url = str(record.get("url") or "")
# Keyword matching is substring-based, so only the URL host may participate:
# full URLs (e.g. Google News base64 paths) randomly contain substrings like
# "llm"/"gpt" and turn unrelated world news into "AI" items.
try:
url_host = (urlparse(url).netloc or "").lower()
except Exception:
url_host = ""
text = f"{title} {source} {site_name} {url_host}".lower()
ai_signals = matched_keywords(text, AI_KEYWORDS)
if CURSOR_SIGNAL_RE.search(text) and "cursor" not in ai_signals:
ai_signals = sorted(ai_signals + ["cursor"])
tech_signals = matched_keywords(text, TECH_KEYWORDS)
noise = matched_keywords(text, NOISE_KEYWORDS) + matched_keywords(text, COMMERCE_NOISE_KEYWORDS)
source_prior = SOURCE_PRIORS.get(site_id, 0.0)
if contains_unsafe_promotional_content(text):
return _result(
is_ai_related=False,
score=0.0,
label="unsafe_content",
reason="unsafe_promotional_content",
signals=[],
noise=["unsafe_promotional_content"],
)
if site_id == "curated_media":
source_l = source.lower()
title_l = title.lower()
trusted_source = contains_any_keyword(source_l, CURATED_MEDIA_TRUSTED_SOURCE_KEYWORDS)
research_source = contains_any_keyword(source_l, CURATED_MEDIA_RESEARCH_SOURCE_KEYWORDS)
title_has_ai = contains_meaningful_ai_signal(title_l)
title_has_broad_ai = contains_any_keyword(title_l, list(BROAD_AI_TERMS)) or EN_SIGNAL_RE.search(title_l) is not None
title_has_research = contains_any_keyword(title_l, CURATED_MEDIA_RESEARCH_TERMS)
if research_source and not (title_has_ai or title_has_research):
return _result(
is_ai_related=False,
score=0.22,
label="source_scope_drop",
reason="curated_research_source_requires_research_or_ai_title_signal",
signals=ai_signals + tech_signals,
noise=noise,
)
if not (trusted_source or research_source or title_has_ai or (title_has_broad_ai and bool(tech_signals))):
return _result(
is_ai_related=False,
score=source_prior + (0.28 if title_has_broad_ai else 0.0),
label="source_scope_drop",
reason="curated_media_requires_ai_title_or_trusted_ai_feed",
signals=ai_signals + tech_signals,
noise=noise,
)
if research_source or title_has_research:
label = "research_paper"
elif contains_any_keyword(title_l, CURATED_MEDIA_BUSINESS_TERMS):
label = "industry_business"
else:
label = _label_for_text(text, bool(tech_signals))
base = 0.58 if trusted_source else 0.5
score = source_prior + base + min(0.12, 0.03 * len(ai_signals)) + min(0.08, 0.02 * len(tech_signals))
if research_source:
score = min(score, 0.76)
if noise and not title_has_ai:
score -= min(0.16, 0.04 * len(noise))
return _result(
is_ai_related=score >= AI_RELEVANCE_THRESHOLD,
score=score,
label=label,
reason="curated_media_source_filter",
signals=ai_signals + tech_signals or ([source_l] if trusted_source else []),
noise=noise,
)
if site_id in AI_DEFAULT_SOURCES:
return _result(
is_ai_related=True,
score=max(AI_RELEVANCE_THRESHOLD, 0.72 + source_prior),
label=_label_for_text(text, bool(tech_signals)),
reason="trusted_ai_source_default_keep",
signals=ai_signals or [site_id],
noise=noise,
)
has_ai = contains_meaningful_ai_signal(text)
has_broad_ai = contains_any_keyword(text, list(BROAD_AI_TERMS)) or EN_SIGNAL_RE.search(text) is not None
has_tech = bool(tech_signals)
if not (has_ai or (has_broad_ai and has_tech)):
return _result(
is_ai_related=False,
score=source_prior + (0.32 if has_broad_ai else 0.0) + (0.08 if has_tech else 0.0),
label="not_ai",
reason="missing_meaningful_ai_signal",
signals=ai_signals + tech_signals,
noise=noise,
)
if contains_any_keyword(text, COMMERCE_NOISE_KEYWORDS) and not has_ai:
return _result(
is_ai_related=False,
score=0.25 + source_prior,
label="commerce_noise",
reason="commerce_noise_without_strong_ai_signal",
signals=ai_signals + tech_signals,
noise=noise,
)
if contains_any_keyword(text, NOISE_KEYWORDS) and not has_ai:
return _result(
is_ai_related=False,
score=0.25 + source_prior,
label="noise",
reason="noise_without_strong_ai_signal",
signals=ai_signals + tech_signals,
noise=noise,
)
score = source_prior + (0.52 if has_ai else 0.34) + min(0.18, 0.04 * len(ai_signals)) + min(0.12, 0.03 * len(tech_signals))
if noise:
score -= min(0.18, 0.04 * len(noise))
if has_broad_ai and has_tech and not has_ai:
score = max(score, AI_RELEVANCE_THRESHOLD)
if has_ai:
score = max(score, AI_RELEVANCE_THRESHOLD)
return _result(
is_ai_related=True,
score=score,
label=_label_for_text(text, has_tech),
reason="matched_ai_signal" if has_ai else "matched_broad_ai_plus_tech_signal",
signals=ai_signals + tech_signals,
noise=noise,
)
def is_ai_related_record(record: dict[str, Any]) -> bool:
return bool(score_ai_relevance(record)["is_ai_related"])
def is_broadly_ai_related(record: dict[str, Any]) -> bool:
"""Return True when a record clears the broad-AI floor (score >= 0.3).
This is a looser gate than ``is_ai_related_record`` (which requires >= 0.65).
Used by the "all-mode" UI view to filter out obviously-irrelevant noise while
keeping items with at least tangential AI/tech signal.
"""
return score_ai_relevance(record)["score"] >= AI_BROAD_RELEVANCE_FLOOR
def add_ai_relevance_fields(record: dict[str, Any]) -> dict[str, Any]:
relevance = score_ai_relevance(record)
out = dict(record)
out["ai_is_related"] = relevance["is_ai_related"]
out["ai_score"] = relevance["score"]
out["ai_label"] = relevance["label"]
out["ai_relevance_reason"] = relevance["reason"]
out["ai_signals"] = relevance["signals"]
out["ai_noise"] = relevance["noise"]
return out
@@ -0,0 +1,414 @@
#!/usr/bin/env python3
"""Evaluate whether a candidate source overlaps too much with existing sources.
This script is intentionally maintainer-facing. It does not change the daily
news pipeline; it produces an intake report that helps decide whether a new RSS
source should become a public default, remain an advanced OPML source, or be
skipped as too duplicative.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from collections import Counter
from datetime import UTC, datetime, timedelta
from difflib import SequenceMatcher
from pathlib import Path
from typing import Any
import requests
# Allow `python scripts/evaluate_source_overlap.py ...` from the repo root while
# keeping package imports working under pytest.
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from scripts.update_news import ( # noqa: E402
event_time,
iso,
normalize_url,
parse_date_any,
parse_feed_entries_via_xml,
utc_now,
)
TITLE_SOURCE_SUFFIXES = {
"ai hot",
"aihot",
"hacker news",
"product hunt",
"techcrunch",
"the verge",
"venturebeat",
}
TITLE_DROP_WORDS = {
"exclusive",
"breaking",
"news",
"the",
"a",
"an",
"from",
"by",
"via",
}
ENTITY_TERMS = {
"openai",
"anthropic",
"claude",
"google",
"gemini",
"deepseek",
"qwen",
"llama",
"meta",
"mistral",
"perplexity",
"cursor",
"codex",
"copilot",
"github",
"runway",
"kling",
}
def normalize_title_for_overlap(title: str) -> str:
"""Normalize a title for overlap comparison, not for display."""
text = (title or "").strip().lower()
if not text:
return ""
# Drop common source suffixes like "— AI HOT" when they are clearly not part
# of the story title.
parts = re.split(r"\s+[—–-]\s+", text)
if len(parts) > 1 and parts[-1].strip(" .") in TITLE_SOURCE_SUFFIXES:
text = " — ".join(parts[:-1])
# Remove bracketed labels such as [Exclusive], not bracketed product names.
text = re.sub(r"\[(exclusive|breaking|update|news)\]", " ", text, flags=re.I)
text = re.sub(r"\b20\d{2}\b", " ", text)
text = re.sub(r"[^a-z0-9\u4e00-\u9fff]+", " ", text)
tokens = [token for token in text.split() if token not in TITLE_DROP_WORDS]
return " ".join(tokens)
def title_similarity(a: str, b: str) -> float:
"""Return a stable 0-1 title similarity score with light token reordering."""
na = normalize_title_for_overlap(a)
nb = normalize_title_for_overlap(b)
if not na or not nb:
return 0.0
if na == nb:
return 1.0
seq_score = SequenceMatcher(None, na, nb).ratio()
ta = set(na.split())
tb = set(nb.split())
if not ta or not tb:
return round(seq_score, 3)
token_score = len(ta & tb) / len(ta | tb)
sorted_score = SequenceMatcher(None, " ".join(sorted(ta)), " ".join(sorted(tb))).ratio()
return round(max(seq_score, token_score, sorted_score), 3)
def extract_entities(title: str) -> set[str]:
normalized = normalize_title_for_overlap(title)
tokens = set(normalized.split())
return {term for term in ENTITY_TERMS if term in tokens}
def tokens_for_overlap(title: str) -> set[str]:
return {token for token in normalize_title_for_overlap(title).split() if len(token) > 1}
def _days_apart(a: dict[str, Any], b: dict[str, Any]) -> float | None:
ta = event_time(a)
tb = event_time(b)
if not ta or not tb:
return None
return abs((ta - tb).total_seconds()) / 86400
def classify_overlap(
candidate: dict[str, Any],
existing: dict[str, Any],
*,
title_threshold: float = 0.88,
possible_title_threshold: float = 0.62,
) -> dict[str, Any] | None:
"""Classify overlap between one candidate item and one existing record."""
candidate_url = normalize_url(str(candidate.get("url") or ""))
existing_url = normalize_url(str(existing.get("url") or ""))
score = 0.0
match_type = ""
hard_duplicate = False
if candidate_url and existing_url and candidate_url == existing_url:
score = 1.0
match_type = "url_exact"
hard_duplicate = True
else:
candidate_title = str(candidate.get("title") or "")
existing_title = str(existing.get("title") or "")
score = title_similarity(candidate_title, existing_title)
if normalize_title_for_overlap(candidate_title) == normalize_title_for_overlap(existing_title) and candidate_title.strip().lower() == existing_title.strip().lower():
match_type = "title_exact"
hard_duplicate = True
elif score >= title_threshold:
match_type = "title_similarity"
hard_duplicate = True
else:
candidate_entities = extract_entities(str(candidate.get("title") or ""))
existing_entities = extract_entities(str(existing.get("title") or ""))
days = _days_apart(candidate, existing)
if (
score >= possible_title_threshold
and candidate_entities
and candidate_entities & existing_entities
and (days is None or days <= 2)
):
match_type = "entity_time_possible"
hard_duplicate = False
else:
return None
return {
"candidate_title": candidate.get("title"),
"candidate_url": candidate_url,
"matched_title": existing.get("title"),
"matched_url": existing_url,
"matched_site_id": existing.get("site_id"),
"matched_site_name": existing.get("site_name"),
"match_type": match_type,
"score": round(score, 3),
"hard_duplicate": hard_duplicate,
}
def make_recommendation(item_count: int, duplicate_rate: float) -> dict[str, Any]:
sample_too_small = item_count < 5
if sample_too_small:
decision = "watchlist"
reason = "样本少于5条,不建议仅凭重复率直接拒绝;先进入观察列表。"
elif duplicate_rate >= 0.65:
decision = "skip_duplicate"
reason = "最近内容和已有信源高度重复,默认不录入公共源。"
elif duplicate_rate >= 0.35:
decision = "watchlist"
reason = "重复率中等,建议先作为OPML高级源或观察源,而不是直接进入默认源。"
else:
decision = "accept_default"
reason = "重复率较低,能为默认源补充明显新增信息。"
return {
"decision": decision,
"reason": reason,
"sample_too_small": sample_too_small,
}
def filter_recent_records(records: list[dict[str, Any]], now: datetime, lookback_days: int) -> list[dict[str, Any]]:
cutoff = now - timedelta(days=lookback_days)
out = []
for record in records:
ts = event_time(record)
if ts and ts >= cutoff:
out.append(record)
return out
def evaluate_source_overlap(
candidate_items: list[dict[str, Any]],
baseline_items: list[dict[str, Any]],
*,
candidate: dict[str, Any],
generated_at: datetime,
lookback_days: int,
) -> dict[str, Any]:
matches: list[dict[str, Any]] = []
possible_matches: list[dict[str, Any]] = []
duplicate_candidate_indexes: set[int] = set()
candidate_site_id = str(candidate.get("site_id") or "")
baseline = [item for item in baseline_items if str(item.get("site_id") or "") != candidate_site_id]
url_index: dict[str, list[dict[str, Any]]] = {}
token_index: dict[str, set[int]] = {}
for baseline_idx, existing in enumerate(baseline):
url = normalize_url(str(existing.get("url") or ""))
if url:
url_index.setdefault(url, []).append(existing)
for token in tokens_for_overlap(str(existing.get("title") or "")):
token_index.setdefault(token, set()).add(baseline_idx)
for idx, item in enumerate(candidate_items):
best_hard: dict[str, Any] | None = None
best_possible: dict[str, Any] | None = None
candidate_url = normalize_url(str(item.get("url") or ""))
candidates_to_compare: list[dict[str, Any]] = []
if candidate_url in url_index:
candidates_to_compare.extend(url_index[candidate_url])
else:
candidate_indexes: set[int] = set()
for token in tokens_for_overlap(str(item.get("title") or "")):
candidate_indexes.update(token_index.get(token, set()))
candidates_to_compare.extend(baseline[i] for i in candidate_indexes)
for existing in candidates_to_compare:
match = classify_overlap(item, existing)
if not match:
continue
if match["hard_duplicate"]:
if best_hard is None or match["score"] > best_hard["score"]:
best_hard = match
elif best_possible is None or match["score"] > best_possible["score"]:
best_possible = match
if best_hard:
duplicate_candidate_indexes.add(idx)
matches.append(best_hard)
elif best_possible:
possible_matches.append(best_possible)
item_count = len(candidate_items)
duplicate_count = len(duplicate_candidate_indexes)
possible_duplicate_count = len(possible_matches)
unique_count = max(0, item_count - duplicate_count - possible_duplicate_count)
duplicate_rate = round(duplicate_count / item_count, 3) if item_count else 0.0
unique_rate = round(unique_count / item_count, 3) if item_count else 0.0
source_counter = Counter(str(match.get("matched_site_id") or "") for match in matches if match.get("matched_site_id"))
name_by_id = {
str(match.get("matched_site_id") or ""): str(match.get("matched_site_name") or match.get("matched_site_id") or "")
for match in matches
}
return {
"generated_at": iso(generated_at),
"candidate": {
"site_id": candidate_site_id,
"site_name": candidate.get("site_name") or candidate_site_id,
"url": candidate.get("url"),
"item_count": item_count,
"lookback_days": lookback_days,
},
"baseline": {
"source_count": len({str(item.get("site_id") or "") for item in baseline if item.get("site_id")}),
"item_count": len(baseline),
"window_days": lookback_days,
},
"overlap": {
"duplicate_count": duplicate_count,
"possible_duplicate_count": possible_duplicate_count,
"unique_count": unique_count,
"duplicate_rate": duplicate_rate,
"unique_rate": unique_rate,
},
"top_overlapping_sources": [
{
"site_id": site_id,
"site_name": name_by_id.get(site_id) or site_id,
"matched_count": count,
}
for site_id, count in source_counter.most_common(10)
],
"recommendation": make_recommendation(item_count=item_count, duplicate_rate=duplicate_rate),
"matches": matches,
"possible_matches": possible_matches,
}
def load_archive_records(path: Path) -> list[dict[str, Any]]:
data = json.loads(path.read_text(encoding="utf-8"))
if isinstance(data, dict):
if "items" in data and isinstance(data["items"], list):
return [item for item in data["items"] if isinstance(item, dict)]
return [item for item in data.values() if isinstance(item, dict)]
if isinstance(data, list):
return [item for item in data if isinstance(item, dict)]
raise ValueError(f"Unsupported baseline JSON shape: {path}")
def fetch_rss_candidate(source_url: str, source_name: str, site_id: str, now: datetime) -> list[dict[str, Any]]:
resp = requests.get(source_url, timeout=25, headers={"User-Agent": "AI-News-Radar/0.3 SourceOverlapCheck"})
resp.raise_for_status()
entries = parse_feed_entries_via_xml(resp.content)
out: list[dict[str, Any]] = []
for entry in entries:
title = str(entry.get("title") or "").strip()
url = normalize_url(str(entry.get("link") or entry.get("url") or ""))
if not title or not url.startswith("http"):
continue
published = parse_date_any(entry.get("published") or entry.get("updated") or entry.get("pubDate"), now)
out.append(
{
"site_id": site_id,
"site_name": source_name,
"source": source_name,
"title": title,
"url": url,
"published_at": iso(published),
"first_seen_at": iso(now),
}
)
return out
def print_summary(report: dict[str, Any]) -> None:
candidate = report["candidate"]
overlap = report["overlap"]
recommendation = report["recommendation"]
print(f"Source: {candidate['site_name']} ({candidate['site_id']})")
print(f"Items: {candidate['item_count']} | Baseline: {report['baseline']['item_count']}")
print(
"Duplicate rate: "
f"{overlap['duplicate_rate']:.3f} "
f"({overlap['duplicate_count']} hard, {overlap['possible_duplicate_count']} possible)"
)
print(f"Unique rate: {overlap['unique_rate']:.3f} ({overlap['unique_count']} unique)")
print(f"Recommendation: {recommendation['decision']} — {recommendation['reason']}")
def main() -> int:
parser = argparse.ArgumentParser(description="Evaluate candidate source overlap against AI News Radar baseline")
parser.add_argument("--source-url", required=True, help="Candidate RSS/Atom URL")
parser.add_argument("--source-name", required=True, help="Human-readable candidate source name")
parser.add_argument("--site-id", default="candidate", help="Candidate site_id used in the report")
parser.add_argument("--baseline", default="data/archive.json", help="Baseline archive/latest JSON path")
parser.add_argument("--lookback-days", type=int, default=7, help="Recent window to compare")
parser.add_argument("--output", default="", help="Optional JSON report output path")
args = parser.parse_args()
now = utc_now()
baseline_path = Path(args.baseline).expanduser()
baseline_items = filter_recent_records(load_archive_records(baseline_path), now, max(1, args.lookback_days))
candidate_items = filter_recent_records(
fetch_rss_candidate(args.source_url, args.source_name, args.site_id, now),
now,
max(1, args.lookback_days),
)
report = evaluate_source_overlap(
candidate_items,
baseline_items,
candidate={"site_id": args.site_id, "site_name": args.source_name, "url": args.source_url},
generated_at=now,
lookback_days=max(1, args.lookback_days),
)
if args.output:
output_path = Path(args.output).expanduser()
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"Wrote overlap report: {output_path}")
print_summary(report)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,514 @@
#!/usr/bin/env python3
"""Persona scoring for the daily brief.
Reads ``{data-dir}/daily-brief.json`` produced by ``update_news.py``, scores
each item with a persona-flavored LLM call (DeepSeek), writes the persona
fields back into ``daily-brief.json``, and generates a multi-persona TOP3
review file ``{data-dir}/top3-personas.json``.
Design constraints:
- Standalone: communicates with the rest of the pipeline only through JSON
files. Never imports ``update_news.py``.
- Zero new dependencies: standard library plus ``requests``.
- Runs without any API key: falls back to a rules-based score derived from
``importance_score`` so the public repo stays runnable key-free.
- Exit code is always 0 except for argument errors or corrupted input JSON.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
import requests
DEFAULT_API_BASE_URL = "https://api.deepseek.com"
DEFAULT_MODEL = "deepseek-chat"
CACHE_VERSION = 1
CACHE_MAX_AGE_DAYS = 21
REVIEW_MAX_CHARS = 60
RETRY_BACKOFF_SECONDS = 2.0
ITEM_CONTEXT_FIELDS = (
"story_id",
"title",
"url",
"importance_score",
"importance_label",
"category",
"reasons",
"source_count",
)
PERSONA_ID_RE = re.compile(r"^[a-z-]+$")
CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
WHITESPACE_RE = re.compile(r"\s+")
class PersonaError(Exception):
"""Raised for invalid persona files."""
def parse_frontmatter(text: str) -> tuple[dict, str]:
"""Parse a ``---`` delimited frontmatter block of simple ``key: value`` lines.
Returns (metadata dict, body). Raises PersonaError when the block is
missing or malformed.
"""
lines = text.split("\n")
if not lines or lines[0].strip() != "---":
raise PersonaError("missing frontmatter opening '---'")
meta: dict = {}
end_index = None
for i, line in enumerate(lines[1:], start=1):
if line.strip() == "---":
end_index = i
break
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if ":" not in stripped:
raise PersonaError(f"invalid frontmatter line: {line!r}")
key, _, value = stripped.partition(":")
key = key.strip()
value = value.strip()
if value.lower() in {"true", "false"}:
meta[key] = value.lower() == "true"
else:
meta[key] = value
if end_index is None:
raise PersonaError("missing frontmatter closing '---'")
body = "\n".join(lines[end_index + 1 :]).strip()
return meta, body
def load_personas(personas_dir: Path) -> list[dict]:
"""Load persona definitions from ``personas_dir``.
Each persona is a dict: id, name, name_en, default, prompt, sha8 (first 8
hex chars of the sha1 of the full file text).
"""
personas = []
if not personas_dir.is_dir():
return personas
for path in sorted(personas_dir.glob("*.md")):
if path.name.lower() == "readme.md":
continue
text = path.read_text(encoding="utf-8")
try:
meta, body = parse_frontmatter(text)
except PersonaError as exc:
print(f"persona: skipping {path.name}: {exc}", file=sys.stderr)
continue
persona_id = str(meta.get("id", "")).strip()
if not PERSONA_ID_RE.match(persona_id):
print(
f"persona: skipping {path.name}: invalid id {persona_id!r}",
file=sys.stderr,
)
continue
personas.append(
{
"id": persona_id,
"name": str(meta.get("name", persona_id)),
"name_en": str(meta.get("name_en", persona_id)),
"default": bool(meta.get("default", False)),
"prompt": body,
"sha8": hashlib.sha1(text.encode("utf-8")).hexdigest()[:8],
}
)
return personas
def pick_default_persona(personas: list[dict]) -> dict | None:
for persona in personas:
if persona.get("default"):
return persona
return personas[0] if personas else None
def sanitize_review(review: str) -> str:
review = CONTROL_CHARS_RE.sub("", str(review))
review = WHITESPACE_RE.sub(" ", review).strip()
return review[:REVIEW_MAX_CHARS]
def clamp_score(value) -> int:
try:
score = int(round(float(value)))
except (TypeError, ValueError):
score = 0
return max(0, min(100, score))
def title_hash(title: str) -> str:
return hashlib.sha1(str(title).encode("utf-8")).hexdigest()[:8]
def cache_key(story_id: str, persona: dict) -> str:
return f"{story_id}|{persona['id']}|{persona['sha8']}"
def load_cache(path: Path) -> dict:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, ValueError):
return {"version": CACHE_VERSION, "entries": {}}
if not isinstance(data, dict) or data.get("version") != CACHE_VERSION:
return {"version": CACHE_VERSION, "entries": {}}
entries = data.get("entries")
if not isinstance(entries, dict):
entries = {}
return {"version": CACHE_VERSION, "entries": entries}
def prune_cache(cache: dict, now: datetime) -> None:
cutoff = now - timedelta(days=CACHE_MAX_AGE_DAYS)
kept = {}
for key, entry in cache.get("entries", {}).items():
if not isinstance(entry, dict):
continue
scored_at = entry.get("scored_at")
try:
when = datetime.fromisoformat(str(scored_at).replace("Z", "+00:00"))
except (TypeError, ValueError):
continue
if when.tzinfo is None:
when = when.replace(tzinfo=timezone.utc)
if when >= cutoff:
kept[key] = entry
cache["entries"] = kept
def save_cache(path: Path, cache: dict, now: datetime) -> None:
prune_cache(cache, now)
path.write_text(
json.dumps(cache, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
def build_item_context(item: dict) -> dict:
context = {}
for field in ITEM_CONTEXT_FIELDS:
if field in item:
context[field] = item[field]
sources = item.get("sources")
if isinstance(sources, list):
context["sources"] = [
{"source": src.get("source")}
for src in sources
if isinstance(src, dict) and src.get("source")
]
return context
def call_persona_api(
persona: dict,
item: dict,
*,
api_key: str,
base_url: str,
model: str,
timeout: float,
) -> tuple[int, str] | None:
"""Call the DeepSeek chat completions API for one item with one persona.
Retries once on failure (2s backoff). Returns (score, review) or None.
"""
url = f"{base_url.rstrip('/')}/chat/completions"
payload = {
"model": model,
"messages": [
{"role": "system", "content": persona["prompt"]},
{
"role": "user",
"content": json.dumps(build_item_context(item), ensure_ascii=False),
},
],
"response_format": {"type": "json_object"},
"temperature": 0.3,
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
last_error = None
for attempt in range(2):
if attempt:
time.sleep(RETRY_BACKOFF_SECONDS)
try:
response = requests.post(url, json=payload, headers=headers, timeout=timeout)
if response.status_code == 429:
last_error = "rate limited (429)"
continue
response.raise_for_status()
body = response.json()
content = body["choices"][0]["message"]["content"]
parsed = json.loads(content)
score = clamp_score(parsed.get("score"))
review = sanitize_review(parsed.get("review", ""))
if not review:
last_error = "empty review"
continue
return score, review
except (requests.RequestException, KeyError, IndexError, TypeError, ValueError, json.JSONDecodeError) as exc:
last_error = str(exc)
continue
print(
f"persona: {persona['id']} failed for {item.get('story_id')}: {last_error}",
file=sys.stderr,
)
return None
def score_with_persona(
persona: dict,
item: dict,
cache: dict,
*,
api_key: str,
base_url: str,
model: str,
timeout: float,
stats: dict,
) -> tuple[int, str] | None:
"""Score one item with one persona, using the cache when possible."""
story_id = str(item.get("story_id", ""))
key = cache_key(story_id, persona)
thash = title_hash(item.get("title", ""))
entry = cache["entries"].get(key)
if isinstance(entry, dict) and entry.get("title_hash") == thash:
stats["cached"] += 1
return clamp_score(entry.get("score")), sanitize_review(entry.get("review", ""))
result = call_persona_api(
persona,
item,
api_key=api_key,
base_url=base_url,
model=model,
timeout=timeout,
)
if result is None:
stats["failed"] += 1
return None
score, review = result
cache["entries"][key] = {
"score": score,
"review": review,
"title_hash": thash,
"scored_at": utcnow_iso(),
}
stats["scored"] += 1
return score, review
def utcnow_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
def run_fallback(items: list[dict], default_persona: dict | None) -> None:
persona_id = default_persona["id"] if default_persona else "pragmatic"
scored_at = utcnow_iso()
for item in items:
item["persona_id"] = persona_id
item["persona_score"] = clamp_score(item.get("importance_score", 0))
item.pop("persona_review", None)
item["persona_meta"] = {"mode": "rules_fallback", "scored_at": scored_at}
def build_top3_payload(
items: list[dict],
personas: list[dict],
cache: dict,
*,
top3: int,
api_key: str,
base_url: str,
model: str,
timeout: float,
stats: dict,
) -> dict:
ranked = sorted(
[item for item in items if "persona_score" in item],
key=lambda it: (
-float(it.get("persona_score", 0)),
-float(it.get("importance_score", 0) or 0),
),
)[:top3]
top_items = []
for rank, item in enumerate(ranked, start=1):
reviews = {}
for persona in personas:
result = score_with_persona(
persona,
item,
cache,
api_key=api_key,
base_url=base_url,
model=model,
timeout=timeout,
stats=stats,
)
if result is None:
continue
score, review = result
reviews[persona["id"]] = {"score": score, "review": review}
top_items.append(
{
"story_id": item.get("story_id"),
"title": item.get("title"),
"url": item.get("url"),
"rank": rank,
"reviews": reviews,
}
)
return {
"generated_at": utcnow_iso(),
"model": model,
"personas": [{"id": p["id"], "name": p["name"]} for p in personas],
"items": top_items,
}
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Persona scoring for daily brief")
parser.add_argument("--data-dir", default="data", help="data directory")
parser.add_argument("--personas-dir", default="personas", help="personas directory")
parser.add_argument("--max-items", type=int, default=40, help="max items to score")
parser.add_argument("--top3", type=int, default=3, help="TOP N multi-persona items")
parser.add_argument("--timeout", type=float, default=30, help="API timeout seconds")
parser.add_argument(
"--dry-run", action="store_true", help="run without writing any files"
)
parser.add_argument(
"--list-personas", action="store_true", help="list personas and exit"
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
personas_dir = Path(args.personas_dir)
personas = load_personas(personas_dir)
default_persona = pick_default_persona(personas)
if args.list_personas:
if not personas:
print("persona: no personas found")
return 0
for persona in personas:
marker = " (default)" if persona is default_persona else ""
print(f"{persona['id']}\t{persona['name']} / {persona['name_en']}{marker}")
return 0
data_dir = Path(args.data_dir)
brief_path = data_dir / "daily-brief.json"
top3_path = data_dir / "top3-personas.json"
cache_path = data_dir / "persona-cache.json"
if not brief_path.is_file():
print(f"persona: {brief_path} not found, nothing to do")
print("persona: scored=0 cached=0 skipped=0 failed=0")
return 0
brief = json.loads(brief_path.read_text(encoding="utf-8"))
all_items = brief.get("items", [])
if not isinstance(all_items, list):
raise SystemExit(f"persona: {brief_path} has invalid 'items'")
items = all_items[: args.max_items]
skipped = len(all_items) - len(items)
api_key = os.environ.get("DEEPSEEK_API_KEY", "").strip()
base_url = os.environ.get("DEEPSEEK_API_BASE_URL", "").strip() or DEFAULT_API_BASE_URL
model = os.environ.get("DEEPSEEK_MODEL", "").strip() or DEFAULT_MODEL
enabled = os.environ.get("PERSONA_ENABLED", "").strip() != "0"
now = datetime.now(timezone.utc)
stats = {"scored": 0, "cached": 0, "failed": 0}
if not api_key or not enabled or default_persona is None:
run_fallback(items, default_persona)
top3_payload = {"generated_at": utcnow_iso(), "items": []}
if not args.dry_run:
brief_path.write_text(
json.dumps(brief, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
top3_path.write_text(
json.dumps(top3_payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(
f"persona: scored=0 cached=0 skipped={skipped} failed=0"
)
return 0
cache = load_cache(cache_path)
scored_at = utcnow_iso()
for item in items:
result = score_with_persona(
default_persona,
item,
cache,
api_key=api_key,
base_url=base_url,
model=model,
timeout=args.timeout,
stats=stats,
)
if result is None:
continue
score, review = result
item["persona_id"] = default_persona["id"]
item["persona_score"] = score
item["persona_review"] = review
item["persona_meta"] = {
"mode": "llm",
"model": model,
"scored_at": scored_at,
}
top3_payload = build_top3_payload(
items,
personas,
cache,
top3=args.top3,
api_key=api_key,
base_url=base_url,
model=model,
timeout=args.timeout,
stats=stats,
)
if not args.dry_run:
brief_path.write_text(
json.dumps(brief, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
top3_path.write_text(
json.dumps(top3_payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
save_cache(cache_path, cache, now)
print(
"persona: scored={scored} cached={cached} skipped={skipped} failed={failed}".format(
scored=stats["scored"],
cached=stats["cached"],
skipped=skipped,
failed=stats["failed"],
)
)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Run the pinned generator with a required output directory outside this skill."""
from __future__ import annotations
import argparse
import runpy
import sys
from pathlib import Path
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", required=True, help="Absolute private working/output directory, outside the installed skill")
args, remaining = parser.parse_known_args()
if any(arg == "--output-dir" or arg.startswith("--output-dir=") for arg in remaining):
parser.error("supply --output-dir exactly once")
output = Path(args.output_dir).expanduser()
if not output.is_absolute():
parser.error("--output-dir must be absolute")
output = output.resolve()
skill = Path(__file__).resolve().parents[1]
if output == skill or skill in output.parents:
parser.error("--output-dir must be outside the installed skill")
sys.dont_write_bytecode = True
sys.path.insert(0, str(skill / "scripts"))
sys.argv = [str(skill / "scripts" / "update_news.py"), "--output-dir", str(output), *remaining]
runpy.run_path(sys.argv[0], run_name="__main__")
if __name__ == "__main__":
main()
File diff suppressed because it is too large. Load diff