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:
parent
fa745ee3f7
commit
d40244900e
6 changed files with 757 additions and 11 deletions
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import json
|
||||
import re
|
||||
|
||||
|
|
@ -193,6 +194,7 @@ def parse_map_scores(
|
|||
"n": n,
|
||||
"article": article,
|
||||
"article_id": article.get("id"),
|
||||
"title": article.get("title"),
|
||||
"score": score,
|
||||
"importance": importance,
|
||||
"category": _category_from_block(block_text),
|
||||
|
|
@ -243,3 +245,198 @@ def select_graded(
|
|||
def join_blocks(blocks: list[dict]) -> str:
|
||||
"""Reduce-phase DATA text: only these blocks, original text, best-first."""
|
||||
return "\n\n".join(b["text"] for b in blocks)
|
||||
|
||||
|
||||
# ── Syndication dedupe (pure string work — no LLM, no DB) ──────────────────
|
||||
|
||||
DEFAULT_DEDUPE_SIMILARITY = 0.85
|
||||
|
||||
# Wire copy carries the station at the end of the headline: " - KCCI", " | CNN".
|
||||
_SOURCE_SEPARATORS = (" - ", " | ", " — ", " – ")
|
||||
_MAX_SUFFIX_CHARS = 40
|
||||
_MAX_SUFFIX_WORDS = 4
|
||||
_NON_ALNUM_RE = re.compile(r"[^a-z0-9]+")
|
||||
_DIGIT_RE = re.compile(r"\d")
|
||||
|
||||
|
||||
def normalize_title(title) -> str:
|
||||
"""Comparable headline form: lowercase, source suffix stripped, words only.
|
||||
|
||||
A trailing `` - KCCI`` / `` | CNN`` / `` — AP`` marker is removed when the
|
||||
tail is short (<= 40 chars and <= 4 words) **and carries no digits**, so
|
||||
``Story - KCCI`` and ``Story | WTAE`` land on the same key while serial
|
||||
titles (``… – Part 1`` / ``… – Part 2``, ``… — Day 5``) stay distinct.
|
||||
Titles that are None, empty or non-string normalise to ``""`` and never
|
||||
match anything.
|
||||
"""
|
||||
if title is None:
|
||||
return ""
|
||||
if not isinstance(title, str):
|
||||
title = str(title)
|
||||
text = title.strip().lower()
|
||||
cut = -1
|
||||
for separator in _SOURCE_SEPARATORS:
|
||||
idx = text.rfind(separator)
|
||||
if idx <= 0:
|
||||
continue
|
||||
tail = text[idx + len(separator):].strip()
|
||||
if (
|
||||
len(tail) <= _MAX_SUFFIX_CHARS
|
||||
and 0 < len(tail.split()) <= _MAX_SUFFIX_WORDS
|
||||
and not _DIGIT_RE.search(tail)
|
||||
):
|
||||
cut = max(cut, idx)
|
||||
if cut > 0:
|
||||
text = text[:cut]
|
||||
return " ".join(_NON_ALNUM_RE.sub(" ", text).split())
|
||||
|
||||
|
||||
def title_similarity(normalised_left: str, normalised_right: str) -> float:
|
||||
"""0..1 story-similarity of two already-normalised titles.
|
||||
|
||||
Max of word-set Jaccard (word order and repetition do not matter) and the
|
||||
``difflib`` ratio over the *word sequence* (so near-verbatim rewrites
|
||||
score high, while short headlines differing only in a name — "story 1" vs
|
||||
"story 2", "storm hits Texas" vs "storm hits Tennessee" — stay low).
|
||||
"""
|
||||
if not normalised_left or not normalised_right:
|
||||
return 0.0
|
||||
if normalised_left == normalised_right:
|
||||
return 1.0
|
||||
words_left = normalised_left.split()
|
||||
words_right = normalised_right.split()
|
||||
set_left, set_right = set(words_left), set(words_right)
|
||||
union = set_left | set_right
|
||||
jaccard = len(set_left & set_right) / len(union) if union else 0.0
|
||||
ratio = difflib.SequenceMatcher(None, words_left, words_right).ratio()
|
||||
return max(jaccard, ratio)
|
||||
|
||||
|
||||
def _block_title(block: dict):
|
||||
"""Title of a graded block: the parsed key, else the nested article row."""
|
||||
title = block.get("title")
|
||||
if title is None:
|
||||
article = block.get("article")
|
||||
if isinstance(article, dict):
|
||||
title = article.get("title")
|
||||
return title
|
||||
|
||||
|
||||
def _block_score(block: dict) -> int:
|
||||
try:
|
||||
return int(block.get("score") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _block_position(block: dict, fallback: int) -> int:
|
||||
position = block.get("position")
|
||||
return position if isinstance(position, int) else fallback
|
||||
|
||||
|
||||
def _categories_conflict(left: dict, right: dict) -> bool:
|
||||
"""True when both blocks carry a category and the two differ."""
|
||||
cat_left = str(left.get("category") or "").strip().lower()
|
||||
cat_right = str(right.get("category") or "").strip().lower()
|
||||
return bool(cat_left) and bool(cat_right) and cat_left != cat_right
|
||||
|
||||
|
||||
def _numbers_conflict(left: str, right: str) -> bool:
|
||||
"""True when the two titles disagree on any number.
|
||||
|
||||
Syndicated wire copy is verbatim, so a differing figure ("… – Part 1" vs
|
||||
"… – Part 2", "12 dead" vs "21 dead", horoscope date boilerplate) means a
|
||||
different story — never collapse it on string similarity alone.
|
||||
"""
|
||||
digits_left = {word for word in left.split() if _DIGIT_RE.search(word)}
|
||||
digits_right = {word for word in right.split() if _DIGIT_RE.search(word)}
|
||||
return digits_left != digits_right
|
||||
|
||||
|
||||
def dedupe_blocks(
|
||||
blocks: list[dict],
|
||||
*,
|
||||
similarity: float = DEFAULT_DEDUPE_SIMILARITY,
|
||||
enabled: bool = True,
|
||||
) -> tuple[list[dict], dict]:
|
||||
"""Collapse syndicated copies of one story into a single representative block.
|
||||
|
||||
Blocks are visited best-score-first (ties -> earliest position), so each
|
||||
cluster's representative is its highest-scoring block and a dropped block
|
||||
never survives. Matching is against the representative only (star
|
||||
clustering, no transitive chaining); two titles match when their normalised
|
||||
forms are equal or ``title_similarity`` clears ``similarity``. Blocks whose
|
||||
categories are both set and different are never merged, and neither are
|
||||
titles that disagree on any number (wire copy is verbatim; a different
|
||||
figure is a different story). Blocks without a usable title stay unique.
|
||||
Never raises: empty/None input and malformed blocks are tolerated.
|
||||
|
||||
Returns ``(kept_blocks, stats)``; kept blocks keep their original order.
|
||||
``stats["duplicate_blocks"]`` holds one record per dropped block::
|
||||
|
||||
{"index", "article_id", "position", "score", "title",
|
||||
"duplicate_of", "duplicate_of_position", "similarity", "block"}
|
||||
"""
|
||||
items = [block for block in (blocks or []) if isinstance(block, dict)]
|
||||
try:
|
||||
threshold = float(similarity)
|
||||
except (TypeError, ValueError):
|
||||
threshold = DEFAULT_DEDUPE_SIMILARITY
|
||||
threshold = min(1.0, max(0.0, threshold))
|
||||
stats = {
|
||||
"input": len(items),
|
||||
"kept": len(items),
|
||||
"duplicates": 0,
|
||||
"threshold": threshold,
|
||||
"duplicate_blocks": [],
|
||||
}
|
||||
if not enabled or len(items) < 2:
|
||||
return list(items), stats
|
||||
|
||||
ranked = sorted(
|
||||
range(len(items)),
|
||||
key=lambda i: (-_block_score(items[i]), _block_position(items[i], i), i),
|
||||
)
|
||||
# groups: representative index -> normalised representative title
|
||||
groups: list[dict] = []
|
||||
for index in ranked:
|
||||
block = items[index]
|
||||
norm = normalize_title(_block_title(block))
|
||||
match: tuple[dict, float] | None = None
|
||||
if norm:
|
||||
for group in groups:
|
||||
rep_norm = group["norm"]
|
||||
if (
|
||||
not rep_norm
|
||||
or _categories_conflict(block, items[group["index"]])
|
||||
or _numbers_conflict(norm, rep_norm)
|
||||
):
|
||||
continue
|
||||
score = 1.0 if norm == rep_norm else title_similarity(norm, rep_norm)
|
||||
if score >= threshold:
|
||||
match = (group, score)
|
||||
break
|
||||
if match is None:
|
||||
groups.append({"index": index, "norm": norm})
|
||||
continue
|
||||
group, score = match
|
||||
rep = items[group["index"]]
|
||||
stats["duplicate_blocks"].append(
|
||||
{
|
||||
"index": index,
|
||||
"article_id": block.get("article_id"),
|
||||
"position": _block_position(block, index),
|
||||
"score": _block_score(block),
|
||||
"title": _block_title(block),
|
||||
"duplicate_of": rep.get("article_id"),
|
||||
"duplicate_of_position": _block_position(rep, group["index"]),
|
||||
"similarity": round(score, 4),
|
||||
"block": block,
|
||||
}
|
||||
)
|
||||
|
||||
dropped = {record["index"] for record in stats["duplicate_blocks"]}
|
||||
kept = [block for index, block in enumerate(items) if index not in dropped]
|
||||
stats["kept"] = len(kept)
|
||||
stats["duplicates"] = len(stats["duplicate_blocks"])
|
||||
return kept, stats
|
||||
|
|
|
|||
Loading…
Reference in a new issue