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.
This commit is contained in:
parent
d04ddc9afa
commit
653e02b09f
3 changed files with 298 additions and 4 deletions
|
|
@ -291,6 +291,69 @@ def normalize_title(title) -> str:
|
||||||
return " ".join(_NON_ALNUM_RE.sub(" ", text).split())
|
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:
|
def title_similarity(normalised_left: str, normalised_right: str) -> float:
|
||||||
"""0..1 story-similarity of two already-normalised titles.
|
"""0..1 story-similarity of two already-normalised titles.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ from zoneinfo import ZoneInfo
|
||||||
import psycopg2
|
import psycopg2
|
||||||
|
|
||||||
from intel import (
|
from intel import (
|
||||||
|
article_url_for_row,
|
||||||
dedupe_blocks,
|
dedupe_blocks,
|
||||||
join_blocks,
|
join_blocks,
|
||||||
parse_map_scores,
|
parse_map_scores,
|
||||||
|
|
@ -511,9 +512,19 @@ def _already_recapped_today() -> bool:
|
||||||
|
|
||||||
|
|
||||||
def save_batch(
|
def save_batch(
|
||||||
summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval"
|
summary_en: str,
|
||||||
|
model: str,
|
||||||
|
ticker: list,
|
||||||
|
map_items: list,
|
||||||
|
*,
|
||||||
|
kind: str = "interval",
|
||||||
|
articles: list | None = None,
|
||||||
) -> int | None:
|
) -> int | None:
|
||||||
"""Insert the master brief plus flagged ticker/map rows. Returns the new summary id."""
|
"""Insert the master brief plus flagged ticker/map rows. Returns the new summary id.
|
||||||
|
|
||||||
|
``news_items.url`` is the matched selected article's url, never the model's
|
||||||
|
``url`` field. A null article url is stored as ``""``.
|
||||||
|
"""
|
||||||
ticker_rows = select_ticker(ticker or [])
|
ticker_rows = select_ticker(ticker or [])
|
||||||
map_rows = select_map(map_items or [])
|
map_rows = select_map(map_items or [])
|
||||||
text = (summary_en or "").strip()
|
text = (summary_en or "").strip()
|
||||||
|
|
@ -547,7 +558,7 @@ def save_batch(
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
row.get("url"),
|
article_url_for_row(row, articles),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
for row in map_rows:
|
for row in map_rows:
|
||||||
|
|
@ -563,7 +574,7 @@ def save_batch(
|
||||||
row.get("lon"),
|
row.get("lon"),
|
||||||
row.get("location_confidence"),
|
row.get("location_confidence"),
|
||||||
row.get("category"),
|
row.get("category"),
|
||||||
row.get("url"),
|
article_url_for_row(row, articles),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
@ -786,12 +797,18 @@ def summarize_news() -> None:
|
||||||
logger.warning("Reduce phase returned empty — nothing to persist.")
|
logger.warning("Reduce phase returned empty — nothing to persist.")
|
||||||
return
|
return
|
||||||
parsed = parse_reduce_json(master_raw)
|
parsed = parse_reduce_json(master_raw)
|
||||||
|
selected_articles = [
|
||||||
|
block["article"]
|
||||||
|
for block in selected
|
||||||
|
if isinstance(block.get("article"), dict)
|
||||||
|
]
|
||||||
summary_id = save_batch(
|
summary_id = save_batch(
|
||||||
parsed["summary_en"],
|
parsed["summary_en"],
|
||||||
model,
|
model,
|
||||||
parsed["ticker"],
|
parsed["ticker"],
|
||||||
parsed["map_items"],
|
parsed["map_items"],
|
||||||
kind="daily_recap" if recap else "interval",
|
kind="daily_recap" if recap else "interval",
|
||||||
|
articles=selected_articles,
|
||||||
)
|
)
|
||||||
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
|
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
|
||||||
|
|
||||||
|
|
|
||||||
214
news/summerizer/tests/test_article_url.py
Normal file
214
news/summerizer/tests/test_article_url.py
Normal file
|
|
@ -0,0 +1,214 @@
|
||||||
|
"""Ticker and map rows persist the selected article URL, never the model's."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import summarizer
|
||||||
|
from intel import article_url_for_row
|
||||||
|
|
||||||
|
|
||||||
|
ARTICLES = [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Strike in Kyiv",
|
||||||
|
"content": "x" * 120,
|
||||||
|
"url": "https://ex.com/1",
|
||||||
|
"domain": "ex.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Floods in Paris",
|
||||||
|
"content": "y" * 120,
|
||||||
|
"url": "https://ex.com/2",
|
||||||
|
"domain": "ex.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Quiet day in Oslo",
|
||||||
|
"content": "z" * 120,
|
||||||
|
"url": None,
|
||||||
|
"domain": "ex.com",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _block(n: int, score: int) -> str:
|
||||||
|
return "\n".join(
|
||||||
|
[
|
||||||
|
f"Article {n}:",
|
||||||
|
f"- Score: {score}",
|
||||||
|
"- Importance: high",
|
||||||
|
"- Fact bullet",
|
||||||
|
"- Location: Kyiv",
|
||||||
|
"- Category: politics",
|
||||||
|
"- Lat: 50.45",
|
||||||
|
"- Lon: 30.52",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
REDUCE = {
|
||||||
|
"summary_en": "Lead: strike in Kyiv. Also floods in Paris and a quiet day in Oslo.",
|
||||||
|
# Headlines are swapped vs article order so a positional stamp would cross-wire.
|
||||||
|
# Model url is blank or a decoy — neither may be stored.
|
||||||
|
"ticker": [
|
||||||
|
{"headline": "Floods in Paris", "importance": "high", "url": ""},
|
||||||
|
{
|
||||||
|
"headline": "Strike in Kyiv",
|
||||||
|
"importance": "critical",
|
||||||
|
"url": "https://wrong.example/model",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"headline": "Quiet day in Oslo",
|
||||||
|
"importance": "high",
|
||||||
|
"url": "https://invented.example",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"map_items": [
|
||||||
|
{
|
||||||
|
"headline": "Floods in Paris",
|
||||||
|
"importance": "high",
|
||||||
|
"location_name": "Paris",
|
||||||
|
"lat": 48.85,
|
||||||
|
"lon": 2.35,
|
||||||
|
"location_confidence": "city",
|
||||||
|
"category": "environment/disaster",
|
||||||
|
"url": "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"headline": "Strike in Kyiv",
|
||||||
|
"importance": "critical",
|
||||||
|
"location_name": "Kyiv",
|
||||||
|
"lat": 50.45,
|
||||||
|
"lon": 30.52,
|
||||||
|
"location_confidence": "city",
|
||||||
|
"category": "military/conflict",
|
||||||
|
"url": "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"headline": "Quiet day in Oslo",
|
||||||
|
"importance": "high",
|
||||||
|
"location_name": "Oslo",
|
||||||
|
"lat": 59.91,
|
||||||
|
"lon": 10.75,
|
||||||
|
"location_confidence": "city",
|
||||||
|
"category": "society",
|
||||||
|
"url": "https://invented.example",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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 _news_item_urls(db_log: list, kind: str) -> list:
|
||||||
|
urls = []
|
||||||
|
for entry in db_log:
|
||||||
|
if entry[0] != "execute" or "INSERT INTO news_items" not in entry[1]:
|
||||||
|
continue
|
||||||
|
params = entry[2]
|
||||||
|
if not params or params[1] != kind:
|
||||||
|
continue
|
||||||
|
urls.append(params[-1])
|
||||||
|
return urls
|
||||||
|
|
||||||
|
|
||||||
|
def test_matcher_uses_article_url_not_model_url():
|
||||||
|
row = {"headline": "Strike in Kyiv", "importance": "critical", "url": ""}
|
||||||
|
assert article_url_for_row(row, ARTICLES) == "https://ex.com/1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_matcher_does_not_cross_wire_and_null_url_stays_blank():
|
||||||
|
paris = {"headline": "Floods in Paris", "url": "https://ex.com/1"}
|
||||||
|
oslo = {"headline": "Quiet day in Oslo", "url": "https://invented.example"}
|
||||||
|
assert article_url_for_row(paris, ARTICLES) == "https://ex.com/2"
|
||||||
|
assert article_url_for_row(oslo, ARTICLES) == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_matcher_refuses_a_tie_instead_of_guessing():
|
||||||
|
twins = [
|
||||||
|
{"title": "Same story", "url": "https://ex.com/1"},
|
||||||
|
{"title": "Same story", "url": "https://ex.com/2"},
|
||||||
|
]
|
||||||
|
assert article_url_for_row({"headline": "Same story", "url": ""}, twins) == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_unmatched_headline_does_not_invent_a_url():
|
||||||
|
row = {"headline": "Unrelated market tape", "url": "https://model.example/kept"}
|
||||||
|
assert article_url_for_row(row, ARTICLES) == ""
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def harness(monkeypatch):
|
||||||
|
calls: list[tuple[str, str]] = []
|
||||||
|
db_log: list = []
|
||||||
|
map_reply = "\n\n".join([_block(1, 92), _block(2, 88), _block(3, 80)])
|
||||||
|
reduce_reply = json.dumps(REDUCE)
|
||||||
|
|
||||||
|
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_reply
|
||||||
|
|
||||||
|
monkeypatch.setenv("NOUS_API_KEY", "test-key")
|
||||||
|
monkeypatch.setenv("SUMMARY_MODEL", "test-model")
|
||||||
|
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 test_persist_stamps_article_url_on_ticker_and_map(harness):
|
||||||
|
_, db_log = harness
|
||||||
|
summarizer.summarize_news()
|
||||||
|
|
||||||
|
assert _news_item_urls(db_log, "ticker") == [
|
||||||
|
"https://ex.com/2",
|
||||||
|
"https://ex.com/1",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
assert _news_item_urls(db_log, "map") == [
|
||||||
|
"https://ex.com/2",
|
||||||
|
"https://ex.com/1",
|
||||||
|
"",
|
||||||
|
]
|
||||||
Loading…
Reference in a new issue