osint-dashboard/news/summerizer/intel.py
Sirius DevOps 653e02b09f fix(summarizer): stamp ticker and map urls from the article, not the model
The reduce model returns url="" and save_batch was persisting that blank.
Match each headline to a selected article title and store that article's
url. A null article url or an ambiguous match stores "" — never a guessed
or model-supplied URL.
2026-11-14 00:32:43 -05:00

505 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
from __future__ import annotations
import difflib
import json
import re
_EMPTY = {"summary_en": "", "ticker": [], "map_items": []}
_KEEP = frozenset({"critical", "high"})
_RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3}
_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
MAP_CAP = 20
# ── 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)
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:
flagged = []
medium = []
low = []
for row in rows:
imp = row.get("importance")
if imp not in _RANK:
continue
headline = _trimmed_headline(row, TICKER_HEADLINE_MAX)
if not headline:
continue
item = dict(row)
item["headline"] = headline
if imp in _KEEP:
flagged.append(item)
elif imp == "medium":
medium.append(item)
else:
low.append(item)
if len(flagged) >= TICKER_CAP:
break
if flagged:
return flagged[:TICKER_CAP]
return (medium + low)[:TICKER_CAP]
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)
if len(out) >= MAP_CAP:
break
return out
# ── 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"),
"title": article.get("title"),
"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(
blocks: list[dict],
*,
min_score: int,
top_n: int,
fallback_top: int,
fallback_min_score: int = 0,
) -> 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
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.
"""
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
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
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())
# Headline must clear this to take an article URL. Above the
# "storm hits Texas" vs "storm hits Tennessee" band (~0.67) so a near-miss
# cannot steal another story's URL. A tie stores "" — a wrong URL is worse
# than a blank one.
ARTICLE_URL_MIN_SIMILARITY = 0.85
# Word-sequence containment only counts when the shorter side is specific.
_URL_CONTAIN_MIN_WORDS = 4
def _contains_word_sequence(outer: str, inner: str) -> bool:
outer_words = outer.split()
inner_words = inner.split()
if len(inner_words) < _URL_CONTAIN_MIN_WORDS or len(inner_words) > len(outer_words):
return False
width = len(inner_words)
return any(
outer_words[i : i + width] == inner_words
for i in range(len(outer_words) - width + 1)
)
def article_url_for_row(row: dict, articles: list | None) -> str:
"""URL of the selected article this ticker/map row refers to, else ``""``.
Matches the row headline to an article title. Never reads the model's
``url`` field. A null, missing, or non-string article url stores ``""``.
Two articles that score the same (or no article that clears the bar)
store ``""`` so a headline cannot be wired to the wrong story.
"""
if not isinstance(row, dict):
return ""
headline = normalize_title(row.get("headline"))
if not headline:
return ""
best_score = 0.0
best: list[dict] = []
for article in articles or []:
if not isinstance(article, dict):
continue
title = normalize_title(article.get("title"))
if not title:
continue
if headline == title:
score = 1.0
elif _contains_word_sequence(headline, title) or _contains_word_sequence(title, headline):
score = 0.95
else:
score = title_similarity(headline, title)
if score + 1e-9 < ARTICLE_URL_MIN_SIMILARITY:
continue
if score > best_score + 1e-9:
best_score = score
best = [article]
elif abs(score - best_score) <= 1e-9:
best.append(article)
if len(best) != 1:
return ""
url = best[0].get("url")
if not isinstance(url, str):
return ""
return url.strip()
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