diff --git a/.env.example b/.env.example index def97d4..b23921c 100644 --- a/.env.example +++ b/.env.example @@ -107,6 +107,16 @@ SUMMARY_MIN_SCORE=60 SUMMARY_TOP_N=12 SUMMARY_FALLBACK_TOP=3 SUMMARY_FALLBACK_MIN_SCORE=40 +# Syndication dedupe: the same wire story arrives from many station domains +# (kcci.com, wtae.com, …) with an identical headline. Copies are collapsed +# before the threshold/cap, so SUMMARY_TOP_N buys distinct stories: normalised +# titles (lowercase, trailing " - KCCI"/" | CNN"/" — AP" source suffix dropped) +# count as one story when they are equal or >= SUMMARY_DEDUPE_SIMILARITY alike. +# The highest-scoring copy represents the story; the rest are still written to +# article_scores with selected=false and duplicate_of = the surviving article id. +# Set SUMMARY_DEDUPE=0 to skip dedupe entirely (old behaviour). +SUMMARY_DEDUPE=1 +SUMMARY_DEDUPE_SIMILARITY=0.85 SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. diff --git a/alembic/versions/013_article_scores_duplicate_of.py b/alembic/versions/013_article_scores_duplicate_of.py new file mode 100644 index 0000000..2fcfb8b --- /dev/null +++ b/alembic/versions/013_article_scores_duplicate_of.py @@ -0,0 +1,23 @@ +"""article_scores.duplicate_of: link a syndicated copy to its representative + +Revision ID: 013_article_scores_duplicate_of +Revises: 012_article_scores +Create Date: 2026-11-13 +""" + +from alembic import op + +revision = "013_article_scores_duplicate_of" +down_revision = "012_article_scores" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER" + ) + + +def downgrade() -> None: + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS duplicate_of") diff --git a/docs/news.md b/docs/news.md index 9f0a9d2..4d4c545 100644 --- a/docs/news.md +++ b/docs/news.md @@ -89,6 +89,21 @@ promotes an item above its score. Every graded article is persisted to `article_scores` (score, category, selected, model, summary_id) so the operator can tune the thresholds against real data. +Syndicated wire copy is collapsed **before** the threshold and cap, so +`SUMMARY_TOP_N` counts distinct stories instead of stations: the same headline +carried by seven Hearst domains is one story, not seven. Titles are normalised +first (lowercase, punctuation flattened, a trailing ` - KCCI` / ` | CNN` / +` — AP` source suffix dropped when it is short and digit-free), then two blocks +are the same story when the normalised titles are equal or at least +`SUMMARY_DEDUPE_SIMILARITY` similar (default 0.85; word-set Jaccard or +word-sequence `difflib` ratio). The highest-scoring copy represents the story +(ties → earliest); differing `category` values and titles that disagree on any +number are never merged. Duplicates are still written to `article_scores` with +`selected=false` and `duplicate_of` = the surviving `article_id`, so nothing is +lost for tuning. `SUMMARY_DEDUPE=0` disables dedupe entirely; raising +`SUMMARY_DEDUPE_SIMILARITY` toward 0.95 makes it stricter. Dedupe is pure string +work — no extra LLM call. + ## Keys and Settings - **`NOUS_API_KEY`** — paste in the dashboard **Keys** UI (`api_keys` / @@ -270,6 +285,8 @@ map. `summary_en` lands in `article_summaries.summary_text`. | `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). | | `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. | | `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. | +| `SUMMARY_DEDUPE` | `1` | Collapse syndicated wire copies before selection; `0` skips dedupe entirely. | +| `SUMMARY_DEDUPE_SIMILARITY` | `0.85` | Normalised-title similarity at which two blocks count as the same story (1.0 = verbatim only). | | `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). | | `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). | | `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). | diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index 7d3dc15..5cdf13c 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -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 diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index c1daeae..b1d9c85 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -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__": diff --git a/news/summerizer/tests/test_dedupe.py b/news/summerizer/tests/test_dedupe.py new file mode 100644 index 0000000..1f2ae87 --- /dev/null +++ b/news/summerizer/tests/test_dedupe.py @@ -0,0 +1,432 @@ +"""Syndication dedupe: collapse wire copies before the threshold/cap runs.""" + +from __future__ import annotations + +import json + +import pytest + +import summarizer +from intel import ( + DEFAULT_DEDUPE_SIMILARITY, + dedupe_blocks, + normalize_title, + select_graded, + title_similarity, +) + +# Real titles/scores/categories/ids from summary_id=6 (the measured defect): +# 21 graded articles, 9 distinct titles, 12 of them two wire stories. +OBSERVED_RUN = [ + (95, "www.kcci.com", "politics", 17263, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (95, "www.wyff4.com", "politics", 18546, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (95, "www.wtae.com", "politics", 18550, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.koat.com", "politics", 17272, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.ketv.com", "politics", 17291, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.wlky.com", "politics", 18205, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.wbaltv.com", "politics", 18297, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (75, "www.wlky.com", "other", 23748, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (75, "www.wtae.com", "other", 24029, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.kcci.com", "other", 22643, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.ketv.com", "other", 22664, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.koat.com", "other", 22683, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.wbaltv.com", "other", 23708, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (55, "www.wlky.com", "environment/disaster", 23943, + "Wild video shows the moment a tanker struck a docked cruise ship in New Orleans"), + (55, "www.wyff4.com", "other", 24087, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (45, "www.straitstimes.com", "other", 21227, + "Over 600 personnel take part in multi-agency exercise at RTS Link Woodlands North station"), + (30, "nypost.com", "crime", 16888, + "Monster ex-cop sentenced to chemical castration for raping young kids: “We will take his manhood!”"), + (5, "www.excelsior.com.mx", "other", 17414, + ""), + (5, "nypost.com", "sport", 22376, + "Rangers’ Dylan Garand gets full-circle moment in return to British Columbia"), + (5, "nypost.com", "sport", 22427, + "Chargers get harsh reality check from edge rusher as frustration builds: ‘Walk upstairs and ask them’"), + (5, "www.channelnewsasia.com", "sport", 23026, + "Svitolina says daughter remains priority after split from Monfils"), +] + + +def _blocks(rows) -> list[dict]: + return [ + { + "position": index, + "article_id": article_id, + "score": score, + "category": category, + "domain": domain, + "title": title, + "text": f"Article {index + 1}:\n- Score: {score}\n- Title: {title}", + } + for index, (score, domain, category, article_id, title) in enumerate(rows) + ] + + +def _story(title, *, score=90, article_id=None, category="politics", domain="ex.com", position=0): + return { + "position": position, + "article_id": article_id, + "score": score, + "category": category, + "domain": domain, + "title": title, + "text": f"Article {position + 1}:\n- Score: {score}", + } + + +# ── title normalisation ─────────────────────────────────────────────────── + +@pytest.mark.parametrize( + "title,expected", + [ + ("Big story - KCCI", "big story"), + ("Big story | CNN", "big story"), + ("Big story — AP", "big story"), + ("Big story – AP", "big story"), + (" Big STORY!! ", "big story"), + ("Trump–Xi–Putin summit", "trump xi putin summit"), + ], +) +def test_normalize_title(title, expected): + assert normalize_title(title) == expected + + +@pytest.mark.parametrize("title", [None, "", " ", 12345, ["not", "a", "title"]]) +def test_normalize_title_never_raises(title): + assert isinstance(normalize_title(title), str) + + +def test_serial_titles_are_not_treated_as_a_source_suffix(): + assert normalize_title("Governor's Board – Part 1") != normalize_title( + "Governor's Board – Part 2" + ) + + +# ── grouping ────────────────────────────────────────────────────────────── + +def test_exact_title_duplicates_collapse_to_the_best_scoring_copy(): + blocks = _blocks( + [ + (70, "a.com", "politics", 1, "Storm hits the coast"), + (95, "b.com", "politics", 2, "Storm hits the coast - KCCI"), + (80, "c.com", "politics", 3, "Storm hits the coast"), + ] + ) + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 1 + assert kept[0]["article_id"] == 2 # highest score wins, not the earliest + assert stats["input"] == 3 and stats["kept"] == 1 and stats["duplicates"] == 2 + assert {record["article_id"] for record in stats["duplicate_blocks"]} == {1, 3} + assert all( + record["duplicate_of"] == 2 for record in stats["duplicate_blocks"] + ) + assert all( + record["duplicate_of_position"] == 1 for record in stats["duplicate_blocks"] + ) + + +def test_hearst_style_syndication_set_collapses_to_one(): + domains = [ + "www.kcci.com", "www.wtae.com", "www.wyff4.com", "www.wbaltv.com", + "www.koat.com", "www.ketv.com", "www.wlky.com", + ] + headline = "Flights halted at airports across US due to air traffic control problems" + blocks = [ + _story(headline, score=90 - i, article_id=100 + i, domain=domain, position=i) + for i, domain in enumerate(domains) + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 1 + assert kept[0]["article_id"] == 100 + assert stats["duplicates"] == 6 + assert len({record["duplicate_of"] for record in stats["duplicate_blocks"]}) == 1 + + +def test_rewrites_above_the_threshold_merge_and_below_do_not(): + original = "Flights halted at airports across US due to air traffic control communications problems" + u_s_variant = "Flights halted at airports across U.S. due to air traffic control communications problems" + other_story = "Flights halted at airports across US as a snowstorm closes runways" + + assert title_similarity(normalize_title(original), normalize_title(u_s_variant)) >= 0.85 + assert title_similarity(normalize_title(original), normalize_title(other_story)) < 0.85 + + kept, stats = dedupe_blocks( + [_story(original, article_id=1), _story(u_s_variant, article_id=2, score=80)] + ) + assert [block["article_id"] for block in kept] == [1] + assert stats["duplicates"] == 1 + assert stats["duplicate_blocks"][0]["similarity"] >= 0.85 + + kept, stats = dedupe_blocks( + [_story(original, article_id=1), _story(other_story, article_id=2, score=80)] + ) + assert len(kept) == 2 + assert stats["duplicates"] == 0 + + +def test_threshold_is_tunable(): + left = "Storm batters the coast with heavy rain and wind" + right = "Storm batters the coast with heavy rain, flooding and wind" + assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.75)[0]) == 1 + assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.99)[0]) == 2 + + +def test_different_categories_are_never_merged(): + headline = "Officials announce the election result" + blocks = [ + _story(headline, article_id=1, category="politics"), + _story(headline, article_id=2, score=80, category="military/conflict"), + _story(headline, article_id=3, score=70, category=None), + ] + kept, stats = dedupe_blocks(blocks) + # politics != military/conflict -> kept apart; NULL category may join politics. + assert [block["article_id"] for block in kept] == [1, 2] + assert stats["duplicates"] == 1 + assert stats["duplicate_blocks"][0]["article_id"] == 3 + + +def test_titles_disagreeing_on_a_number_stay_separate(): + blocks = [ + _story("Governor's Commutation Advisory Board – Part 1", article_id=1), + _story("Governor's Commutation Advisory Board – Part 2", article_id=2, score=80), + _story("Quake kills 12 in the northern province", article_id=3, score=70), + _story("Quake kills 21 in the northern province", article_id=4, score=60), + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 4 + assert stats["duplicates"] == 0 + + +def test_ties_keep_the_earliest_position(): + blocks = _blocks( + [ + (90, "a.com", "politics", 11, "Identical headline"), + (90, "b.com", "politics", 12, "Identical headline"), + ] + ) + kept, stats = dedupe_blocks(blocks) + assert [block["article_id"] for block in kept] == [11] + assert stats["duplicate_blocks"][0]["duplicate_of"] == 11 + + +def test_kept_blocks_stay_in_original_order(): + blocks = _blocks( + [ + (10, "a.com", "sport", 1, "Rangers beat the Chargers"), + (95, "b.com", "politics", 2, "Summit announced"), + (20, "c.com", "sport", 3, "Svitolina wins in straight sets"), + ] + ) + kept, _ = dedupe_blocks(blocks) + assert [block["article_id"] for block in kept] == [1, 2, 3] + + +# ── robustness ──────────────────────────────────────────────────────────── + +@pytest.mark.parametrize("blocks", [[], None]) +def test_empty_input_is_returned_untouched(blocks): + kept, stats = dedupe_blocks(blocks) + assert kept == [] + assert stats["input"] == 0 and stats["kept"] == 0 and stats["duplicates"] == 0 + + +def test_missing_and_null_titles_are_kept_and_never_merged(): + blocks = [ + {"position": 0, "score": 90, "text": "a"}, # no title key + {"position": 1, "score": 80, "title": None, "text": "b"}, + {"position": 2, "score": 70, "title": "", "text": "c"}, + {"position": 3, "score": 60, "title": " ", "text": "d"}, + {"position": 4, "score": 50, "title": "Real headline", "text": "e"}, + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 5 + assert stats["duplicates"] == 0 + + +def test_malformed_blocks_do_not_raise(): + kept, stats = dedupe_blocks( + [ + "not a dict", + {"position": 0, "score": "high", "title": "Headline", "text": "a"}, + {"position": 1, "score": None, "title": 42, "text": "b"}, + ] + ) + assert len(kept) == 2 + assert stats["input"] == 2 + + +def test_kill_switch_bypasses_everything(): + blocks = _blocks( + [ + (95, "a.com", "politics", 1, "Same headline"), + (94, "b.com", "politics", 2, "Same headline"), + ] + ) + kept, stats = dedupe_blocks(blocks, enabled=False) + assert [block["article_id"] for block in kept] == [1, 2] + assert stats["duplicates"] == 0 + assert stats["kept"] == 2 + + +def test_dedupe_config_reads_the_environment(monkeypatch): + monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) + monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) + assert summarizer.dedupe_config() == (True, DEFAULT_DEDUPE_SIMILARITY) + + monkeypatch.setenv("SUMMARY_DEDUPE", "0") + assert summarizer.dedupe_config()[0] is False + monkeypatch.setenv("SUMMARY_DEDUPE", "off") + assert summarizer.dedupe_config()[0] is False + + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "0.95") + assert summarizer.dedupe_config() == (False, 0.95) + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "nonsense") + assert summarizer.dedupe_config()[1] == DEFAULT_DEDUPE_SIMILARITY + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "7") + assert summarizer.dedupe_config()[1] == 1.0 + + +# ── replay of the measured run (summary id=6) ───────────────────────────── + +def test_replay_of_summary_6_collapses_21_to_9_and_selects_2(): + blocks = _blocks(OBSERVED_RUN) + assert len(blocks) == 21 + assert len({normalize_title(block["title"]) for block in blocks}) == 9 + + kept, stats = dedupe_blocks(blocks) + assert stats["input"] == 21 + assert stats["kept"] == 9 + assert stats["duplicates"] == 12 + assert len(kept) == 9 + + selected, fallback = select_graded(kept, min_score=60, top_n=12, fallback_top=3) + assert fallback is False + assert [block["score"] for block in selected] == [95, 75] + assert [block["article_id"] for block in selected] == [17263, 23748] + + # Every one of the 12 dropped copies points at one of the two survivors. + survivors = {record["duplicate_of"] for record in stats["duplicate_blocks"]} + assert survivors == {17263, 23748} + # 11 dropped copies still score above SUMMARY_MIN_SCORE; none is selected. + dropped_above = [ + record for record in stats["duplicate_blocks"] if record["score"] >= 60 + ] + assert len(dropped_above) == 11 + + +# ── wiring: one article_scores row per graded article ───────────────────── + +class _FakeCursor: + def __init__(self, log: list): + self.log = log + self._sql = "" + + def execute(self, sql, params=None): + self._sql = " ".join(sql.split()) + self.log.append(("execute", self._sql, params)) + + def executemany(self, sql, rows): + self.log.append(("executemany", " ".join(sql.split()), list(rows))) + + def fetchone(self): + if "article_summaries" in self._sql: + return (77,) + return None + + def fetchall(self): + return [] + + def close(self): + pass + + +class _FakeConn: + def __init__(self, log: list): + self.log = log + + def cursor(self): + return _FakeCursor(self.log) + + def commit(self): + pass + + def close(self): + pass + + +def _map_block(n: int, score: int) -> str: + return "\n".join( + [ + f"Article {n}:", + f"- Score: {score}", + "- Fact bullet", + "- Category: politics", + "- Importance: high", + ] + ) + + +def test_duplicates_are_persisted_unselected_with_duplicate_of(monkeypatch): + """Full summarize_news flow: 4 graded articles, 2 of them the same story.""" + summerizer_articles = [ + {"id": 1, "title": "Summit announced in the region", "content": "x" * 120, + "url": "https://a.com/1", "domain": "a.com"}, + {"id": 2, "title": "Summit announced in the region - KCCI", "content": "x" * 120, + "url": "https://b.com/2", "domain": "b.com"}, + {"id": 3, "title": "Tanker strikes a docked cruise ship", "content": "x" * 120, + "url": "https://c.com/3", "domain": "c.com"}, + {"id": 4, "title": "Rangers win in overtime", "content": "x" * 120, + "url": "https://d.com/4", "domain": "d.com"}, + ] + map_reply = "\n\n".join( + [_map_block(1, 95), _map_block(2, 92), _map_block(3, 55), _map_block(4, 5)] + ) + reduce_reply = json.dumps({"summary_en": "Brief.", "ticker": [], "map_items": []}) + db_log: list = [] + prompts: list[str] = [] + + def fake_chat(prompt, *, api_key, model, base_url, json_mode=False): + prompts.append(prompt) + return reduce_reply if json_mode else map_reply + + monkeypatch.setenv("NOUS_API_KEY", "test-key") + monkeypatch.setenv("SUMMARY_MODEL", "test-model") + monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) + monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) + monkeypatch.setattr(summarizer, "BATCH_SIZE", 10) + monkeypatch.setattr(summarizer, "call_llm", fake_chat) + monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: summerizer_articles) + monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False) + monkeypatch.setattr(summarizer, "ensure_tables", lambda: None) + monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _FakeConn(db_log)) + + summarizer.summarize_news() + + reduce_prompt = prompts[-1] + assert "Score: 95" in reduce_prompt + assert "Score: 92" not in reduce_prompt # wire copy never reaches reduce + + rows = [entry[2] for entry in db_log if entry[0] == "executemany"] + assert rows, db_log + by_article = {row[0]: row for row in rows[-1]} + assert sorted(by_article) == [1, 2, 3, 4] # one row per graded article + assert by_article[1][4] is True and by_article[1][6] is None + assert by_article[2][4] is False and by_article[2][6] == 1 # duplicate_of + assert by_article[3][4] is False and by_article[3][6] is None + assert by_article[4][4] is False and by_article[4][6] is None