2026-11-13 21:47:30 -05:00
|
|
|
|
"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
|
2026-08-27 22:21:26 -04:00
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
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.
2026-11-13 22:14:44 -05:00
|
|
|
|
import difflib
|
2026-08-27 22:21:26 -04:00
|
|
|
|
import json
|
|
|
|
|
|
import re
|
|
|
|
|
|
|
|
|
|
|
|
_EMPTY = {"summary_en": "", "ticker": [], "map_items": []}
|
|
|
|
|
|
_KEEP = frozenset({"critical", "high"})
|
2026-08-29 20:40:27 -04:00
|
|
|
|
_RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
2026-08-27 22:21:26 -04:00
|
|
|
|
_THINK_RE = re.compile(r"<think>.*?</think>", re.DOTALL)
|
|
|
|
|
|
_FENCE_RE = re.compile(r"```(?:json)?", re.IGNORECASE)
|
|
|
|
|
|
|
|
|
|
|
|
TICKER_HEADLINE_MAX = 140
|
|
|
|
|
|
MAP_HEADLINE_MAX = 160
|
|
|
|
|
|
TICKER_CAP = 12
|
2026-08-28 00:02:51 -04:00
|
|
|
|
MAP_CAP = 20
|
2026-08-27 22:21:26 -04:00
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
# ── Map-phase grading (score parsing + selection, pure) ────────────────────
|
|
|
|
|
|
# Importance label → stand-in score, used when the map model omits Score:.
|
|
|
|
|
|
IMPORTANCE_SCORE = {"critical": 95, "high": 78, "medium": 50, "low": 22, "none": 5}
|
|
|
|
|
|
NEUTRAL_SCORE = 50
|
|
|
|
|
|
|
|
|
|
|
|
_ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNORECASE | re.MULTILINE)
|
|
|
|
|
|
_SCORE_RE = re.compile(r"Score:\s*(\d{1,3})", re.IGNORECASE)
|
|
|
|
|
|
_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE)
|
|
|
|
|
|
_CATEGORY_RE = re.compile(r"Category:\s*(.+)", re.IGNORECASE)
|
|
|
|
|
|
|
2026-08-27 22:21:26 -04:00
|
|
|
|
|
|
|
|
|
|
def parse_reduce_json(raw: str) -> dict:
|
|
|
|
|
|
try:
|
|
|
|
|
|
text = _THINK_RE.sub("", raw or "")
|
|
|
|
|
|
text = _FENCE_RE.sub("", text)
|
|
|
|
|
|
start = text.find("{")
|
|
|
|
|
|
end = text.rfind("}")
|
|
|
|
|
|
if start == -1 or end == -1 or end < start:
|
|
|
|
|
|
return dict(_EMPTY)
|
|
|
|
|
|
data = json.loads(text[start : end + 1])
|
|
|
|
|
|
if not isinstance(data, dict):
|
|
|
|
|
|
return dict(_EMPTY)
|
|
|
|
|
|
summary = data.get("summary_en", "")
|
|
|
|
|
|
ticker = data.get("ticker", [])
|
|
|
|
|
|
map_items = data.get("map_items", [])
|
|
|
|
|
|
return {
|
|
|
|
|
|
"summary_en": summary if isinstance(summary, str) else "",
|
|
|
|
|
|
"ticker": ticker if isinstance(ticker, list) else [],
|
|
|
|
|
|
"map_items": map_items if isinstance(map_items, list) else [],
|
|
|
|
|
|
}
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return dict(_EMPTY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def clamp_coords(lat, lon) -> tuple[float, float] | None:
|
|
|
|
|
|
try:
|
|
|
|
|
|
lat_f = float(lat)
|
|
|
|
|
|
lon_f = float(lon)
|
|
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
|
|
return None
|
|
|
|
|
|
if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180):
|
|
|
|
|
|
return None
|
|
|
|
|
|
return (lat_f, lon_f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _trimmed_headline(row: dict, limit: int) -> str:
|
|
|
|
|
|
headline = row.get("headline") or ""
|
|
|
|
|
|
if not isinstance(headline, str):
|
|
|
|
|
|
headline = str(headline)
|
|
|
|
|
|
return headline.strip()[:limit]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def select_ticker(rows: list) -> list:
|
2026-08-29 20:40:27 -04:00
|
|
|
|
flagged = []
|
|
|
|
|
|
medium = []
|
|
|
|
|
|
low = []
|
2026-08-27 22:21:26 -04:00
|
|
|
|
for row in rows:
|
2026-08-29 20:40:27 -04:00
|
|
|
|
imp = row.get("importance")
|
|
|
|
|
|
if imp not in _RANK:
|
2026-08-27 22:21:26 -04:00
|
|
|
|
continue
|
|
|
|
|
|
headline = _trimmed_headline(row, TICKER_HEADLINE_MAX)
|
|
|
|
|
|
if not headline:
|
|
|
|
|
|
continue
|
|
|
|
|
|
item = dict(row)
|
|
|
|
|
|
item["headline"] = headline
|
2026-08-29 20:40:27 -04:00
|
|
|
|
if imp in _KEEP:
|
|
|
|
|
|
flagged.append(item)
|
|
|
|
|
|
elif imp == "medium":
|
|
|
|
|
|
medium.append(item)
|
|
|
|
|
|
else:
|
|
|
|
|
|
low.append(item)
|
|
|
|
|
|
if len(flagged) >= TICKER_CAP:
|
2026-08-27 22:21:26 -04:00
|
|
|
|
break
|
2026-08-29 20:40:27 -04:00
|
|
|
|
if flagged:
|
|
|
|
|
|
return flagged[:TICKER_CAP]
|
|
|
|
|
|
return (medium + low)[:TICKER_CAP]
|
2026-08-27 22:21:26 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def select_map(items: list) -> list:
|
|
|
|
|
|
out = []
|
|
|
|
|
|
for row in items:
|
|
|
|
|
|
if row.get("importance") not in _KEEP:
|
|
|
|
|
|
continue
|
|
|
|
|
|
headline = _trimmed_headline(row, MAP_HEADLINE_MAX)
|
|
|
|
|
|
if not headline:
|
|
|
|
|
|
continue
|
|
|
|
|
|
coords = clamp_coords(row.get("lat"), row.get("lon"))
|
|
|
|
|
|
if coords is None:
|
|
|
|
|
|
continue
|
|
|
|
|
|
item = dict(row)
|
|
|
|
|
|
item["headline"] = headline
|
|
|
|
|
|
item["lat"], item["lon"] = coords
|
|
|
|
|
|
out.append(item)
|
2026-08-28 00:02:51 -04:00
|
|
|
|
if len(out) >= MAP_CAP:
|
|
|
|
|
|
break
|
2026-08-27 22:21:26 -04:00
|
|
|
|
return out
|
2026-11-13 21:47:30 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── Map grading ────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
def _clamp_score(value: int) -> int:
|
|
|
|
|
|
return max(0, min(100, int(value)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _score_from_block(text: str) -> tuple[int, bool]:
|
|
|
|
|
|
"""Score for one article block. Second element True when a fallback was used."""
|
|
|
|
|
|
match = _SCORE_RE.search(text)
|
|
|
|
|
|
if match:
|
|
|
|
|
|
try:
|
|
|
|
|
|
return _clamp_score(int(match.group(1))), False
|
|
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
|
|
pass
|
|
|
|
|
|
match = _IMPORTANCE_RE.search(text)
|
|
|
|
|
|
if match:
|
|
|
|
|
|
return IMPORTANCE_SCORE.get(match.group(1).lower(), NEUTRAL_SCORE), True
|
|
|
|
|
|
return NEUTRAL_SCORE, True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _category_from_block(text: str) -> str | None:
|
|
|
|
|
|
match = _CATEGORY_RE.search(text)
|
|
|
|
|
|
if not match:
|
|
|
|
|
|
return None
|
|
|
|
|
|
value = match.group(1).strip().strip("*_` ").rstrip(".").strip()
|
|
|
|
|
|
return value[:40] or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_map_scores(
|
|
|
|
|
|
raw: str, *, articles: list[dict], batch_index: int = 0, batch_size: int = 1
|
|
|
|
|
|
) -> tuple[list[dict], dict]:
|
|
|
|
|
|
"""Split one map response into scored per-article blocks.
|
|
|
|
|
|
|
|
|
|
|
|
Pure: no DB, no logging. Block ``n`` of batch ``b`` is attributed to
|
|
|
|
|
|
``articles[b * batch_size + n - 1]``. Blocks whose ``Article <n>`` number does
|
|
|
|
|
|
not land inside this batch (model omitted/reordered articles) are counted in
|
|
|
|
|
|
``stats["unattributed"]`` and dropped — there is no article row to attribute
|
|
|
|
|
|
them to. Never raises.
|
|
|
|
|
|
|
|
|
|
|
|
Returns ``(blocks, stats)`` where each block is::
|
|
|
|
|
|
|
|
|
|
|
|
{"n", "article", "article_id", "score", "importance", "category",
|
|
|
|
|
|
"text", "position"}
|
|
|
|
|
|
"""
|
|
|
|
|
|
text = raw or ""
|
|
|
|
|
|
matches = list(_ARTICLE_RE.finditer(text))
|
|
|
|
|
|
blocks: list[dict] = []
|
|
|
|
|
|
seen: set[int] = set()
|
|
|
|
|
|
fallback = 0
|
|
|
|
|
|
unattributed = 0
|
|
|
|
|
|
size = max(1, int(batch_size))
|
|
|
|
|
|
for pos, match in enumerate(matches):
|
|
|
|
|
|
try:
|
|
|
|
|
|
n = int(match.group(1))
|
|
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
|
|
unattributed += 1
|
|
|
|
|
|
continue
|
|
|
|
|
|
if n in seen:
|
|
|
|
|
|
unattributed += 1
|
|
|
|
|
|
continue
|
|
|
|
|
|
seen.add(n)
|
|
|
|
|
|
end = matches[pos + 1].start() if pos + 1 < len(matches) else len(text)
|
|
|
|
|
|
block_text = text[match.start():end].strip()
|
|
|
|
|
|
offset = int(batch_index) * size + n - 1
|
|
|
|
|
|
article = articles[offset] if 0 <= offset < len(articles) else None
|
|
|
|
|
|
if article is None or not block_text:
|
|
|
|
|
|
unattributed += 1
|
|
|
|
|
|
continue
|
|
|
|
|
|
score, used_fallback = _score_from_block(block_text)
|
|
|
|
|
|
fallback += 1 if used_fallback else 0
|
|
|
|
|
|
importance = None
|
|
|
|
|
|
imp_match = _IMPORTANCE_RE.search(block_text)
|
|
|
|
|
|
if imp_match:
|
|
|
|
|
|
importance = imp_match.group(1).lower()
|
|
|
|
|
|
blocks.append(
|
|
|
|
|
|
{
|
|
|
|
|
|
"n": n,
|
|
|
|
|
|
"article": article,
|
|
|
|
|
|
"article_id": article.get("id"),
|
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.
2026-11-13 22:14:44 -05:00
|
|
|
|
"title": article.get("title"),
|
2026-11-13 21:47:30 -05:00
|
|
|
|
"score": score,
|
|
|
|
|
|
"importance": importance,
|
|
|
|
|
|
"category": _category_from_block(block_text),
|
|
|
|
|
|
"text": block_text,
|
|
|
|
|
|
"position": offset,
|
|
|
|
|
|
}
|
|
|
|
|
|
)
|
|
|
|
|
|
stats = {
|
|
|
|
|
|
"blocks": len(matches),
|
|
|
|
|
|
"graded": len(blocks),
|
|
|
|
|
|
"fallback": fallback,
|
|
|
|
|
|
"unattributed": unattributed,
|
|
|
|
|
|
}
|
|
|
|
|
|
return blocks, stats
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def select_graded(
|
2026-11-13 21:56:46 -05:00
|
|
|
|
blocks: list[dict],
|
|
|
|
|
|
*,
|
|
|
|
|
|
min_score: int,
|
|
|
|
|
|
top_n: int,
|
|
|
|
|
|
fallback_top: int,
|
|
|
|
|
|
fallback_min_score: int = 0,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
) -> tuple[list[dict], bool]:
|
|
|
|
|
|
"""Rank blocks best-first and return the ones the reduce phase should see.
|
|
|
|
|
|
|
|
|
|
|
|
Keeps ``score >= min_score`` capped at ``top_n`` (stable on ties: original
|
2026-11-13 21:56:46 -05:00
|
|
|
|
order). When nothing clears the bar, returns up to ``fallback_top`` blocks
|
|
|
|
|
|
that also clear ``fallback_min_score`` and True; ``fallback_top == 0``, a
|
|
|
|
|
|
floor that excludes every block, or no blocks at all yield an empty
|
|
|
|
|
|
selection and False.
|
2026-11-13 21:47:30 -05:00
|
|
|
|
"""
|
|
|
|
|
|
ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0))
|
|
|
|
|
|
limit = max(0, int(top_n))
|
|
|
|
|
|
clearing = [b for b in ordered if int(b.get("score") or 0) >= int(min_score)]
|
|
|
|
|
|
if clearing:
|
|
|
|
|
|
return clearing[:limit], False
|
|
|
|
|
|
fallback_limit = max(0, int(fallback_top))
|
|
|
|
|
|
if fallback_limit <= 0:
|
|
|
|
|
|
return [], False
|
2026-11-13 21:56:46 -05:00
|
|
|
|
floor = int(fallback_min_score)
|
|
|
|
|
|
floor_clearing = [b for b in ordered if int(b.get("score") or 0) >= floor]
|
|
|
|
|
|
if not floor_clearing:
|
|
|
|
|
|
return [], False
|
|
|
|
|
|
return floor_clearing[:fallback_limit], True
|
2026-11-13 21:47:30 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
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.
2026-11-13 22:14:44 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── 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
|