feat(summarizer): collapse syndicated wire copies before selection

The map phase grades every article, but a single wire story arrives from
many station domains with an identical headline (the measured run selected
12 blocks that were only two stories, then produced a ticker with five
summit rows and one FAA row). Dedupe now runs before the threshold/cap, so
SUMMARY_TOP_N buys distinct stories.

- intel.py: pure `dedupe_blocks(blocks, *, similarity, enabled)` plus
  `normalize_title` / `title_similarity`. Titles are lowercased, punctuation
  flattened and a short digit-free trailing source suffix (" - KCCI",
  " | CNN", " — AP") dropped; blocks match on equal normalised titles or
  word-set Jaccard / word-sequence difflib ratio >= similarity (default
  0.85). Best score wins the group (ties -> earliest), matching is against
  the representative only (no transitive chaining), and differing categories
  or differing numbers never merge. Blocks now carry their article title.
- summarizer.py: dedupe graded blocks before select_graded() and log
  `dedupe 21 -> 9 (kept 9, duplicates 12)`; SUMMARY_DEDUPE=0 skips it,
  SUMMARY_DEDUPE_SIMILARITY tunes it. persist_article_scores() still writes
  one row per graded article, with duplicates selected=false and
  duplicate_of pointing at the surviving article id.
- article_scores.duplicate_of INTEGER NULL in ensure_tables() and alembic
  013 (upgrade/downgrade verified against Postgres 16).
- docs/news.md + .env.example document both knobs.

Replaying the observed summary id=6 (21 graded, 9 distinct titles) now keeps
9 and, at min_score=60/top_n=12, selects 2 — the 11 dropped copies that
scored >= 60 are stored selected=false with a duplicate_of pointer.
This commit is contained in:
Sirius DevOps 2026-11-13 22:14:44 -05:00
commit d40244900e
6 changed files with 757 additions and 11 deletions

View file

@ -14,6 +14,12 @@ of each summarize_news() — env wins, else api_keys / app_settings:
NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY')
NOUS_BASE_URL default https://inference-api.nousresearch.com/v1
SUMMARY_MODEL default Hermes-4.3-36B (else app_settings)
SUMMARY_MIN_SCORE map-score a block needs to reach the reduce brief (60)
SUMMARY_TOP_N max distinct blocks passed to reduce (12)
SUMMARY_FALLBACK_TOP blocks used when nothing clears MIN_SCORE (3)
SUMMARY_FALLBACK_MIN_SCORE score floor for that fallback set (40)
SUMMARY_DEDUPE "0" disables syndication dedupe (default on)
SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85)
BATCH_SIZE articles per map-phase batch (default 50)
SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set)
NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt)
@ -31,7 +37,15 @@ from zoneinfo import ZoneInfo
import psycopg2
from intel import join_blocks, parse_map_scores, parse_reduce_json, select_graded, select_map, select_ticker
from intel import (
dedupe_blocks,
join_blocks,
parse_map_scores,
parse_reduce_json,
select_graded,
select_map,
select_ticker,
)
from nous_client import chat
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
@ -56,6 +70,10 @@ DEFAULT_SUMMARY_TOP_N = 12
DEFAULT_SUMMARY_FALLBACK_TOP = 3
DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40
# Syndication dedupe (pure string work, runs before the threshold/cap).
DEFAULT_SUMMARY_DEDUPE_SIMILARITY = 0.85
_FALSY = ("0", "false", "no", "off")
def _env_int(name: str, default: int) -> int:
raw = (os.getenv(name) or "").strip()
@ -68,6 +86,26 @@ def _env_int(name: str, default: int) -> int:
return default
def _env_float(name: str, default: float) -> float:
raw = (os.getenv(name) or "").strip()
if not raw:
return default
try:
return float(raw)
except ValueError:
logger.warning("Invalid %s=%r — using default %s", name, raw, default)
return default
def dedupe_config() -> tuple[bool, float]:
"""(enabled, similarity) from env. SUMMARY_DEDUPE=0 skips dedupe entirely."""
enabled = (os.getenv("SUMMARY_DEDUPE") or "1").strip().lower() not in _FALSY
similarity = _env_float(
"SUMMARY_DEDUPE_SIMILARITY", DEFAULT_SUMMARY_DEDUPE_SIMILARITY
)
return enabled, min(1.0, max(0.0, similarity))
def selection_config() -> tuple[int, int, int, int]:
"""(min_score, top_n, fallback_top, fallback_min_score) from env, per run."""
min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE)))
@ -375,9 +413,11 @@ def ensure_tables() -> None:
category TEXT,
selected BOOLEAN NOT NULL,
model TEXT,
duplicate_of INTEGER,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (article_id, created_at)
);
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER;
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
ON article_scores (summary_id);
"""
@ -544,6 +584,9 @@ def persist_article_scores(
) -> None:
"""Insert one article_scores row per graded article (selected true/false).
Syndication duplicates are written too, with ``selected=false`` and
``duplicate_of`` pointing at the surviving article id — the representative
carries the selection even when the copy itself scores above the bar.
Best-effort: a failure here is logged and never aborts the run.
"""
rows = []
@ -551,14 +594,18 @@ def persist_article_scores(
article_id = block.get("article_id")
if article_id is None:
continue
duplicate_of = block.get("duplicate_of")
if not isinstance(duplicate_of, int):
duplicate_of = None
rows.append(
(
article_id,
summary_id,
int(block.get("score") or 0),
block.get("category"),
bool(block.get("selected")),
bool(block.get("selected")) and duplicate_of is None,
model,
duplicate_of,
)
)
if not rows:
@ -568,16 +615,17 @@ def persist_article_scores(
cur = conn.cursor()
cur.executemany(
"INSERT INTO article_scores "
"(article_id, summary_id, score, category, selected, model) "
"VALUES (%s, %s, %s, %s, %s, %s)",
"(article_id, summary_id, score, category, selected, model, duplicate_of) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
rows,
)
conn.commit()
cur.close()
conn.close()
logger.info(
"article_scores persisted rows=%d selected=%d summary_id=%s",
len(rows), sum(1 for r in rows if r[4]), summary_id,
"article_scores persisted rows=%d selected=%d duplicates=%d summary_id=%s",
len(rows), sum(1 for r in rows if r[4]),
sum(1 for r in rows if r[6] is not None), summary_id,
)
except Exception as exc: # noqa: BLE001
logger.error("Error persisting article_scores (run continues): %s", exc)
@ -678,16 +726,35 @@ def summarize_news() -> None:
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
return
dedupe_enabled, dedupe_similarity = dedupe_config()
distinct, dedupe_stats = dedupe_blocks(
graded, similarity=dedupe_similarity, enabled=dedupe_enabled
)
duplicate_blocks = [record["block"] for record in dedupe_stats["duplicate_blocks"]]
for record in dedupe_stats["duplicate_blocks"]:
record["block"]["duplicate_of"] = record["duplicate_of"]
if dedupe_enabled:
logger.info(
"dedupe %d -> %d (kept %d, duplicates %d)",
dedupe_stats["input"], dedupe_stats["kept"],
dedupe_stats["kept"], dedupe_stats["duplicates"],
)
else:
logger.info("dedupe skipped (SUMMARY_DEDUPE=0)")
selected, used_fallback = select_graded(
graded,
distinct,
min_score=min_score,
top_n=top_n,
fallback_top=fallback_top,
fallback_min_score=fallback_min_score,
)
selected_positions = {block["position"] for block in selected}
for block in graded:
for block in distinct:
block["selected"] = block["position"] in selected_positions
for block in duplicate_blocks:
# The representative carries the selection; a wire copy never does.
block["selected"] = False
if used_fallback:
logger.warning(
"No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d "
@ -696,8 +763,8 @@ def summarize_news() -> None:
max(b["score"] for b in graded),
)
logger.info(
"selected %d/%d graded articles for reduce (scores=%s)",
len(selected), len(graded), [b["score"] for b in selected],
"selected %d/%d distinct articles for reduce (scores=%s)",
len(selected), len(distinct), [b["score"] for b in selected],
)
final_input = join_blocks(selected)
@ -726,7 +793,7 @@ def summarize_news() -> None:
parsed["map_items"],
kind="daily_recap" if recap else "interval",
)
persist_article_scores(graded, summary_id=summary_id, model=model)
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
if __name__ == "__main__":