feat(summarizer): score articles in the map phase, brief only the important ones
The map prompt now grades every article 0-100 against an explicit rubric as the first line of its block; the summarizer parses Score:, falls back to the Importance: label when the line is missing, ranks blocks best-first and passes only score >= SUMMARY_MIN_SCORE (capped at SUMMARY_TOP_N) to the reduce phase. - new pure helpers in intel.py: parse_map_scores(), select_graded(), join_blocks() - reduce prompts drop the 'fill the brief with minor incidents and crime' filler instructions and the 'fill ticker with medium then low' clause - new article_scores table (ensure_tables + alembic 012) persists every grade with selected/summary_id/model so thresholds can be tuned from data - SUMMARY_MIN_SCORE (60), SUMMARY_TOP_N (12), SUMMARY_FALLBACK_TOP (3) env knobs
This commit is contained in:
parent
84ea0a17b1
commit
853e87b7c5
8 changed files with 775 additions and 37 deletions
|
|
@ -1,4 +1,4 @@
|
|||
"""Pure parser for the news-summarizer reduce JSON / geo / importance contract."""
|
||||
"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
|
@ -16,6 +16,16 @@ 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:
|
||||
|
|
@ -102,3 +112,123 @@ def select_map(items: list) -> list:
|
|||
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"),
|
||||
"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
|
||||
) -> 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 the top ``fallback_top`` blocks
|
||||
and True; ``fallback_top == 0`` yields an empty selection.
|
||||
"""
|
||||
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
|
||||
return ordered[:fallback_limit], bool(ordered)
|
||||
|
||||
|
||||
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)
|
||||
|
|
|
|||
Loading…
Reference in a new issue