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
202
news/summerizer/tests/test_grading_pipeline.py
Normal file
202
news/summerizer/tests/test_grading_pipeline.py
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
"""Offline end-to-end: map grading feeds a thresholded subset to the reduce phase."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
import summarizer
|
||||
|
||||
|
||||
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 (42,)
|
||||
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):
|
||||
self.log.append(("commit",))
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _articles(n: int = 6) -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"id": i + 1,
|
||||
"title": f"Story {i + 1}",
|
||||
"content": f"Body of story {i + 1} " + "x" * 120,
|
||||
"url": f"https://ex.com/{i + 1}",
|
||||
"domain": "ex.com",
|
||||
}
|
||||
for i in range(n)
|
||||
]
|
||||
|
||||
|
||||
def _block(n: int, score=None, importance=None) -> str:
|
||||
lines = [f"Article {n}:", "- Fact bullet one"]
|
||||
if score is not None:
|
||||
lines.append(f"- Score: {score}")
|
||||
if importance is not None:
|
||||
lines.append(f"- Importance: {importance}")
|
||||
lines += ["- Location: Kyiv", "- Entities: None", "- Category: politics",
|
||||
"- OSINT signal: No notable OSINT signal.", "- Lat: 50.45", "- Lon: 30.52"]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
MAP_REPLIES = [
|
||||
# batch 0 → articles 1..3
|
||||
"\n\n".join([_block(1, score=92), _block(2, score=34), _block(3, score=81)]),
|
||||
# batch 1 → articles 4..6 (numbering restarts; article 6 loses its Score line)
|
||||
"\n\n".join([_block(1, score=12), _block(2, score=66), _block(3, importance="low")]),
|
||||
]
|
||||
|
||||
REDUCE_REPLY = json.dumps(
|
||||
{
|
||||
"summary_en": "Lead: strike in Kyiv. Also: minister resigns.",
|
||||
"ticker": [
|
||||
{"headline": "Strike in Kyiv", "importance": "critical", "url": "https://ex.com/1"},
|
||||
],
|
||||
"map_items": [
|
||||
{
|
||||
"headline": "Strike in Kyiv",
|
||||
"importance": "critical",
|
||||
"location_name": "Kyiv",
|
||||
"lat": 50.45,
|
||||
"lon": 30.52,
|
||||
"location_confidence": "city",
|
||||
"category": "military/conflict",
|
||||
"url": "https://ex.com/1",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(monkeypatch):
|
||||
"""Run summarize_news offline: fake DB, fake LLM, 6 articles, BATCH_SIZE=3."""
|
||||
calls: list[tuple[str, str]] = []
|
||||
db_log: list = []
|
||||
|
||||
def fake_call_llm(prompt, *, api_key, model, base_url, json_mode=False):
|
||||
calls.append(("json" if json_mode else "text", prompt))
|
||||
return REDUCE_REPLY if json_mode else MAP_REPLIES[len(calls) - 1]
|
||||
|
||||
monkeypatch.setenv("NOUS_API_KEY", "test-key")
|
||||
monkeypatch.setenv("SUMMARY_MODEL", "test-model")
|
||||
monkeypatch.setattr(summarizer, "BATCH_SIZE", 3)
|
||||
monkeypatch.setattr(summarizer, "call_llm", fake_call_llm)
|
||||
monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: _articles())
|
||||
monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False)
|
||||
monkeypatch.setattr(summarizer, "_already_recapped_today", lambda: False)
|
||||
monkeypatch.setattr(
|
||||
summarizer.psycopg2, "connect", lambda **kwargs: _FakeConn(db_log)
|
||||
)
|
||||
return calls, db_log
|
||||
|
||||
|
||||
def _score_rows(db_log: list) -> list[tuple]:
|
||||
rows = [entry[2] for entry in db_log if entry[0] == "executemany"]
|
||||
assert rows, f"no executemany in db log: {db_log}"
|
||||
return rows[-1]
|
||||
|
||||
|
||||
def test_reduce_sees_only_articles_above_the_threshold(harness):
|
||||
calls, db_log = harness
|
||||
summarizer.summarize_news()
|
||||
|
||||
reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0]
|
||||
# Selected: 92 (article 1), 81 (article 3), 66 (article 5) — best first.
|
||||
assert reduce_prompt.index("Score: 92") < reduce_prompt.index("Score: 81")
|
||||
assert reduce_prompt.index("Score: 81") < reduce_prompt.index("Score: 66")
|
||||
for leaked in ("Score: 34", "Score: 12", "Importance: low"):
|
||||
assert leaked not in reduce_prompt
|
||||
|
||||
rows = _score_rows(db_log)
|
||||
assert len(rows) == 6
|
||||
by_article = {row[0]: row for row in rows}
|
||||
assert by_article[6][2] == 22 # Importance: low fallback
|
||||
assert sorted(aid for aid, row in by_article.items() if row[4]) == [1, 3, 5]
|
||||
assert {row[1] for row in rows} == {42} # summary_id from save_batch
|
||||
assert {row[5] for row in rows} == {"test-model"}
|
||||
assert by_article[1][3] == "politics"
|
||||
|
||||
|
||||
def test_all_low_scores_fall_back_to_top_three(harness, monkeypatch):
|
||||
calls, db_log = harness
|
||||
monkeypatch.setenv("SUMMARY_MIN_SCORE", "95")
|
||||
monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "3")
|
||||
summarizer.summarize_news()
|
||||
|
||||
reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0]
|
||||
# Top three by score: 92 (article 1), 81 (article 3), 66 (article 5).
|
||||
for kept in ("Score: 92", "Score: 81", "Score: 66"):
|
||||
assert kept in reduce_prompt
|
||||
for dropped in ("Score: 34", "Score: 12", "Importance: low"):
|
||||
assert dropped not in reduce_prompt
|
||||
assert sorted(row[0] for row in _score_rows(db_log) if row[4]) == [1, 3, 5]
|
||||
|
||||
|
||||
def test_fallback_top_zero_sends_empty_data(harness, monkeypatch):
|
||||
calls, db_log = harness
|
||||
monkeypatch.setenv("SUMMARY_MIN_SCORE", "95")
|
||||
monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "0")
|
||||
summarizer.summarize_news()
|
||||
|
||||
reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0]
|
||||
assert "Score: 92" not in reduce_prompt
|
||||
assert reduce_prompt.rstrip().endswith("DATA:")
|
||||
assert not any(row[4] for row in _score_rows(db_log))
|
||||
|
||||
|
||||
def test_score_insert_failure_does_not_abort_the_run(harness, monkeypatch):
|
||||
calls, db_log = harness
|
||||
|
||||
class _BoomConn(_FakeConn):
|
||||
def cursor(self):
|
||||
raise RuntimeError("article_scores unavailable")
|
||||
|
||||
real_connect = summarizer.psycopg2.connect
|
||||
state = {"n": 0}
|
||||
|
||||
def flaky_connect(**kwargs):
|
||||
# First connect = ensure_tables, second = save_batch, third = scores.
|
||||
state["n"] += 1
|
||||
if state["n"] >= 3:
|
||||
return _BoomConn(db_log)
|
||||
return real_connect(**kwargs)
|
||||
|
||||
monkeypatch.setattr(summarizer.psycopg2, "connect", flaky_connect)
|
||||
summarizer.summarize_news() # must not raise
|
||||
|
||||
kinds = [kind for kind, _ in calls]
|
||||
assert kinds.count("json") == 1 # reduce still ran
|
||||
assert any(entry[0] == "execute" and "article_summaries" in entry[1] for entry in db_log)
|
||||
Loading…
Reference in a new issue