2026-08-24 17:28:46 -04:00
|
|
|
|
#!/usr/bin/env python3
|
2026-08-27 23:17:45 -04:00
|
|
|
|
"""News summarizer — Nous map-reduce of scraped articles into brief/ticker/map.
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
2026-08-28 20:53:32 -04:00
|
|
|
|
Reads articles scraped within the last SUMMARY_WINDOW_MINUTES from the shared `articles` table,
|
2026-08-27 23:17:45 -04:00
|
|
|
|
maps them with Nous (per-article English fact blocks), reduces to one JSON
|
|
|
|
|
|
object (summary_en + ticker + map_items), and stores the brief in
|
|
|
|
|
|
`article_summaries` plus flagged rows in `news_items`. Tables live in the
|
|
|
|
|
|
EXISTING osint-db (alembic 003_news + 005_news_items, idempotent).
|
|
|
|
|
|
|
|
|
|
|
|
Everything is env-driven (12-factor). Secrets/config are resolved at the start
|
|
|
|
|
|
of each summarize_news() — env wins, else api_keys / app_settings:
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
DB_HOST / DB_NAME / DB_USER / DB_PASSWORD / DB_PORT PostgreSQL (osint-db)
|
2026-08-27 23:17:45 -04:00
|
|
|
|
NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY')
|
|
|
|
|
|
NOUS_BASE_URL default https://inference-api.nousresearch.com/v1
|
|
|
|
|
|
SUMMARY_MODEL default Hermes-4.3-36B (else app_settings)
|
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
|
|
|
|
SUMMARY_MIN_SCORE map-score a block needs to reach the reduce brief (60)
|
|
|
|
|
|
SUMMARY_TOP_N max distinct blocks passed to reduce (12)
|
|
|
|
|
|
SUMMARY_FALLBACK_TOP blocks used when nothing clears MIN_SCORE (3)
|
|
|
|
|
|
SUMMARY_FALLBACK_MIN_SCORE score floor for that fallback set (40)
|
|
|
|
|
|
SUMMARY_DEDUPE "0" disables syndication dedupe (default on)
|
|
|
|
|
|
SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
BATCH_SIZE articles per map-phase batch (default 50)
|
2026-08-28 20:53:32 -04:00
|
|
|
|
SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set)
|
2026-08-28 22:53:31 -04:00
|
|
|
|
NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt)
|
|
|
|
|
|
NEWS_SUMMARIZE_FORCE "1" to ignore the interval/recap idempotency skip
|
|
|
|
|
|
TZ IANA tz for recap-day bounds (default America/New_York)
|
|
|
|
|
|
INCLUDE_FUTURES legacy; ignored — prompts never inject futures data
|
2026-08-24 17:28:46 -04:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
|
import os
|
|
|
|
|
|
from datetime import datetime
|
2026-08-28 22:53:31 -04:00
|
|
|
|
from zoneinfo import ZoneInfo
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
import psycopg2
|
|
|
|
|
|
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
from gazetteer import fill_block_geo
|
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
|
|
|
|
from intel import (
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
GEO_CONFIDENCES,
|
2026-11-14 00:32:43 -05:00
|
|
|
|
article_url_for_row,
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
clamp_coords,
|
|
|
|
|
|
clean_location_name,
|
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
|
|
|
|
dedupe_blocks,
|
|
|
|
|
|
join_blocks,
|
|
|
|
|
|
parse_map_scores,
|
|
|
|
|
|
parse_reduce_json,
|
|
|
|
|
|
select_graded,
|
|
|
|
|
|
select_map,
|
|
|
|
|
|
select_ticker,
|
|
|
|
|
|
)
|
2026-08-27 23:17:45 -04:00
|
|
|
|
from nous_client import chat
|
|
|
|
|
|
|
2026-08-24 17:28:46 -04:00
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
|
|
|
|
logger = logging.getLogger("news.summarizer")
|
|
|
|
|
|
|
|
|
|
|
|
# ── Configuration (12-factor, container-friendly defaults) ─────────────────
|
|
|
|
|
|
DB_CONFIG = {
|
|
|
|
|
|
"host": os.getenv("DB_HOST", "db").strip(),
|
|
|
|
|
|
"database": os.getenv("DB_NAME", "osint_data").strip(),
|
|
|
|
|
|
"user": os.getenv("DB_USER", "osint").strip(),
|
|
|
|
|
|
"password": os.getenv("DB_PASSWORD", "").strip(),
|
|
|
|
|
|
"port": int(os.getenv("DB_PORT", "5432")),
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
|
|
|
|
|
|
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
2026-08-24 17:28:46 -04:00
|
|
|
|
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
2026-08-28 20:53:32 -04:00
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
# Map-phase grading knobs (operator sets them in the cluster ConfigMap).
|
|
|
|
|
|
DEFAULT_SUMMARY_MIN_SCORE = 60
|
|
|
|
|
|
DEFAULT_SUMMARY_TOP_N = 12
|
|
|
|
|
|
DEFAULT_SUMMARY_FALLBACK_TOP = 3
|
2026-11-13 21:56:46 -05:00
|
|
|
|
DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40
|
2026-11-13 21:47:30 -05:00
|
|
|
|
|
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, runs before the threshold/cap).
|
|
|
|
|
|
DEFAULT_SUMMARY_DEDUPE_SIMILARITY = 0.85
|
|
|
|
|
|
_FALSY = ("0", "false", "no", "off")
|
|
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
|
|
|
|
|
|
def _env_int(name: str, default: int) -> int:
|
|
|
|
|
|
raw = (os.getenv(name) or "").strip()
|
|
|
|
|
|
if not raw:
|
|
|
|
|
|
return default
|
|
|
|
|
|
try:
|
|
|
|
|
|
return int(raw)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
logger.warning("Invalid %s=%r — using default %s", name, raw, default)
|
|
|
|
|
|
return default
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
def _env_float(name: str, default: float) -> float:
|
|
|
|
|
|
raw = (os.getenv(name) or "").strip()
|
|
|
|
|
|
if not raw:
|
|
|
|
|
|
return default
|
|
|
|
|
|
try:
|
|
|
|
|
|
return float(raw)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
logger.warning("Invalid %s=%r — using default %s", name, raw, default)
|
|
|
|
|
|
return default
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def dedupe_config() -> tuple[bool, float]:
|
|
|
|
|
|
"""(enabled, similarity) from env. SUMMARY_DEDUPE=0 skips dedupe entirely."""
|
|
|
|
|
|
enabled = (os.getenv("SUMMARY_DEDUPE") or "1").strip().lower() not in _FALSY
|
|
|
|
|
|
similarity = _env_float(
|
|
|
|
|
|
"SUMMARY_DEDUPE_SIMILARITY", DEFAULT_SUMMARY_DEDUPE_SIMILARITY
|
|
|
|
|
|
)
|
|
|
|
|
|
return enabled, min(1.0, max(0.0, similarity))
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-13 21:56:46 -05:00
|
|
|
|
def selection_config() -> tuple[int, int, int, int]:
|
|
|
|
|
|
"""(min_score, top_n, fallback_top, fallback_min_score) from env, per run."""
|
2026-11-13 21:47:30 -05:00
|
|
|
|
min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE)))
|
|
|
|
|
|
top_n = max(0, _env_int("SUMMARY_TOP_N", DEFAULT_SUMMARY_TOP_N))
|
|
|
|
|
|
fallback_top = max(0, _env_int("SUMMARY_FALLBACK_TOP", DEFAULT_SUMMARY_FALLBACK_TOP))
|
2026-11-13 21:56:46 -05:00
|
|
|
|
fallback_min_score = max(
|
|
|
|
|
|
0, min(100, _env_int("SUMMARY_FALLBACK_MIN_SCORE", DEFAULT_SUMMARY_FALLBACK_MIN_SCORE))
|
|
|
|
|
|
)
|
|
|
|
|
|
return min_score, top_n, fallback_top, fallback_min_score
|
2026-11-13 21:47:30 -05:00
|
|
|
|
|
2026-08-28 20:53:32 -04:00
|
|
|
|
|
|
|
|
|
|
def _summary_window_minutes() -> int:
|
|
|
|
|
|
hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip()
|
|
|
|
|
|
if hours:
|
|
|
|
|
|
return max(1, int(hours) * 60)
|
|
|
|
|
|
mins = (os.getenv("SUMMARY_WINDOW_MINUTES") or "").strip()
|
|
|
|
|
|
if mins:
|
|
|
|
|
|
return max(1, int(mins))
|
|
|
|
|
|
return 15
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _summarize_interval_seconds() -> int:
|
|
|
|
|
|
return max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900")))
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-28 22:53:31 -04:00
|
|
|
|
def is_recap_run() -> bool:
|
|
|
|
|
|
return os.getenv("NEWS_RECAP", "0").lower() in ("1", "true", "yes")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def effective_window_minutes(*, recap: bool | None = None) -> int:
|
|
|
|
|
|
if recap is None:
|
|
|
|
|
|
recap = is_recap_run()
|
|
|
|
|
|
if recap:
|
|
|
|
|
|
return 24 * 60
|
|
|
|
|
|
return _summary_window_minutes()
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-28 20:53:32 -04:00
|
|
|
|
SUMMARY_WINDOW_MINUTES = _summary_window_minutes()
|
2026-08-24 17:28:46 -04:00
|
|
|
|
INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes")
|
|
|
|
|
|
|
|
|
|
|
|
# Only touched when INCLUDE_FUTURES=1 (legacy markets coupling, OSINT-off).
|
|
|
|
|
|
FUTURES_TICKERS = {
|
|
|
|
|
|
"Equity Indices": ["ES=F", "NQ=F", "YM=F", "RTY=F"],
|
|
|
|
|
|
"Energy": ["CL=F", "NG=F", "HO=F", "RB=F"],
|
|
|
|
|
|
"Metals": ["GC=F", "SI=F", "HG=F"],
|
|
|
|
|
|
"Agriculture": ["ZC=F", "ZS=F", "ZW=F", "ZL=F", "KE=F"],
|
|
|
|
|
|
"Currencies": ["6E=F", "6J=F", "6B=F"],
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# ── OSINT-neutral default prompts (env-overridable via MAP_PROMPT/SUMMARY_PROMPT) ──
|
|
|
|
|
|
|
|
|
|
|
|
MAP_PROMPT_DEFAULT = """\
|
|
|
|
|
|
You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts.
|
|
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. Extract every article; the Score below decides what reaches the operator brief.
|
2026-08-28 22:53:31 -04:00
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
Write every field in English. Translate if the article is not English.
|
|
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
Grade every article with this rubric before writing anything else in its block:
|
|
|
|
|
|
|
|
|
|
|
|
- 90–100 — breaking geopolitical/military/security event or major disaster, immediate consequence
|
|
|
|
|
|
- 70–89 — significant national/international politics, conflict, security, infrastructure or disaster news
|
|
|
|
|
|
- 40–69 — notable regional/economic/tech/health story with real consequences
|
|
|
|
|
|
- 10–39 — routine, minor or single-incident crime; local interest
|
|
|
|
|
|
- 0–9 — noise: sport, celebrity, entertainment, market/commodity tape, promotional or event-calendar/schedule listings
|
|
|
|
|
|
|
2026-08-24 17:28:46 -04:00
|
|
|
|
For EACH article in the batch:
|
2026-11-13 21:47:30 -05:00
|
|
|
|
1. Score: the integer 0-100 from the rubric above, first line of the block.
|
|
|
|
|
|
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
|
2026-11-13 21:47:30 -05:00
|
|
|
|
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
|
|
|
|
|
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
|
|
|
|
|
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
|
|
|
|
|
7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score.
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
|
|
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
Output format — strictly one block per article, Score and Importance first:
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
Article 1:
|
2026-11-13 21:47:30 -05:00
|
|
|
|
- Score: <0-100>
|
|
|
|
|
|
- Importance: critical|high|medium|low|none
|
2026-08-24 17:28:46 -04:00
|
|
|
|
- Fact bullet 1
|
|
|
|
|
|
- Fact bullet 2
|
|
|
|
|
|
- Location: ...
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
- Confidence: exact|city|region|country
|
2026-08-24 17:28:46 -04:00
|
|
|
|
- Entities: ...
|
|
|
|
|
|
- Category: ...
|
|
|
|
|
|
- OSINT signal: ...
|
2026-08-27 23:17:45 -04:00
|
|
|
|
- Lat: ...
|
|
|
|
|
|
- Lon: ...
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
Article 2:
|
|
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
Articles in this batch:
|
|
|
|
|
|
{batch_text}
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
SUMMARY_PROMPT_DEFAULT = """\
|
2026-08-28 23:20:40 -04:00
|
|
|
|
You are writing an English operator HUD brief from the article facts in DATA below. Use ONLY that data. Do not invent events, names, dates, places, or implications.
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
2026-08-28 23:20:40 -04:00
|
|
|
|
Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
2026-08-27 23:17:45 -04:00
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
|
|
|
|
|
|
|
|
|
|
|
|
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
2026-08-29 20:40:27 -04:00
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
ticker: only stories present in DATA, highest score first.
|
2026-08-29 20:40:27 -04:00
|
|
|
|
|
|
|
|
|
|
map_items may be empty if no located critical/high event is explicit in the data.
|
2026-08-28 22:53:31 -04:00
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
Demand a single JSON object (no markdown fences) with this exact shape:
|
|
|
|
|
|
|
|
|
|
|
|
{
|
2026-08-28 23:20:40 -04:00
|
|
|
|
"summary_en": "English markdown brief of the provided stories",
|
2026-08-27 23:17:45 -04:00
|
|
|
|
"ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}],
|
|
|
|
|
|
"map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}]
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-29 20:40:27 -04:00
|
|
|
|
ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low.
|
|
|
|
|
|
map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
|
|
|
|
|
summary_en: English markdown executive brief for an operator HUD (4–8 complete bullets or short paragraphs). Cover the actual stories in DATA. Complete — never an unfinished sentence.
|
2026-08-28 22:53:31 -04:00
|
|
|
|
|
|
|
|
|
|
DATA:
|
|
|
|
|
|
{final_input}
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
RECAP_PROMPT_DEFAULT = """\
|
2026-08-28 23:20:40 -04:00
|
|
|
|
You are writing a daily recap of the last 24 hours of news for an OSINT operator HUD, using ONLY the article facts in DATA below. Do not invent events, names, dates, places, or implications.
|
2026-08-28 22:53:31 -04:00
|
|
|
|
|
2026-08-28 23:20:40 -04:00
|
|
|
|
Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
2026-08-28 22:53:31 -04:00
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories of the day and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence.
|
2026-08-29 20:40:27 -04:00
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
|
|
|
|
|
|
|
|
|
|
|
ticker: only stories present in DATA, highest score first.
|
2026-08-28 22:53:31 -04:00
|
|
|
|
|
|
|
|
|
|
Demand a single JSON object (no markdown fences) with this exact shape:
|
|
|
|
|
|
|
|
|
|
|
|
{
|
2026-08-28 23:20:40 -04:00
|
|
|
|
"summary_en": "English markdown daily recap of the provided stories",
|
2026-08-28 22:53:31 -04:00
|
|
|
|
"ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}],
|
|
|
|
|
|
"map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}]
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-29 20:40:27 -04:00
|
|
|
|
ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low.
|
|
|
|
|
|
map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
|
|
|
|
|
summary_en: English markdown daily recap of the last 24 hours. Complete sentences. Cover the actual stories in DATA.
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
DATA:
|
|
|
|
|
|
{final_input}
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── LLM helpers ────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
def _kv(conn, table, name) -> str:
|
|
|
|
|
|
cur = conn.cursor()
|
|
|
|
|
|
cur.execute(f"SELECT value FROM {table} WHERE name = %s", (name,))
|
|
|
|
|
|
row = cur.fetchone()
|
|
|
|
|
|
return (row[0] or "").strip() if row else ""
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
def resolve_api_key() -> str:
|
|
|
|
|
|
env = os.getenv("NOUS_API_KEY", "").strip()
|
|
|
|
|
|
if env:
|
|
|
|
|
|
return env
|
|
|
|
|
|
try:
|
|
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
try:
|
|
|
|
|
|
return _kv(conn, "api_keys", "NOUS_API_KEY")
|
|
|
|
|
|
finally:
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
except Exception: # noqa: BLE001
|
|
|
|
|
|
return ""
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
def resolve_model() -> str:
|
|
|
|
|
|
env = os.getenv("SUMMARY_MODEL", "").strip()
|
|
|
|
|
|
if env:
|
|
|
|
|
|
return env
|
2026-08-24 17:28:46 -04:00
|
|
|
|
try:
|
2026-08-27 23:17:45 -04:00
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
try:
|
|
|
|
|
|
value = _kv(conn, "app_settings", "SUMMARY_MODEL")
|
|
|
|
|
|
return value or DEFAULT_SUMMARY_MODEL
|
|
|
|
|
|
finally:
|
|
|
|
|
|
conn.close()
|
2026-08-24 17:28:46 -04:00
|
|
|
|
except Exception: # noqa: BLE001
|
2026-08-27 23:17:45 -04:00
|
|
|
|
return DEFAULT_SUMMARY_MODEL
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
def resolve_base_url() -> str:
|
|
|
|
|
|
return os.getenv("NOUS_BASE_URL", DEFAULT_NOUS_BASE_URL).strip() or DEFAULT_NOUS_BASE_URL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def call_llm(prompt: str, *, api_key: str, model: str, base_url: str, json_mode: bool = False) -> str:
|
|
|
|
|
|
"""Send a prompt to Nous chat completions and return the text (\"\" on failure)."""
|
|
|
|
|
|
if not api_key:
|
|
|
|
|
|
logger.warning("NOUS_API_KEY not set — skipping LLM call")
|
2026-08-24 17:28:46 -04:00
|
|
|
|
return ""
|
2026-08-27 23:17:45 -04:00
|
|
|
|
return chat(prompt, api_key=api_key, model=model, base_url=base_url, json_mode=json_mode)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── Futures (legacy, gated) ────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
def fetch_current_futures_prices() -> dict:
|
|
|
|
|
|
"""Live futures prices. Only meaningful when INCLUDE_FUTURES=1."""
|
|
|
|
|
|
if not INCLUDE_FUTURES:
|
|
|
|
|
|
return {}
|
|
|
|
|
|
try:
|
|
|
|
|
|
import yfinance as yf # noqa: PLC0415
|
|
|
|
|
|
except ImportError:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
"INCLUDE_FUTURES=1 but yfinance is not installed — install it to enable futures prices"
|
|
|
|
|
|
)
|
|
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
|
|
|
prices: dict = {}
|
|
|
|
|
|
for category, tickers in FUTURES_TICKERS.items():
|
|
|
|
|
|
for ticker in tickers:
|
|
|
|
|
|
try:
|
|
|
|
|
|
data = yf.Ticker(ticker).history(period="1d", interval="1m")
|
|
|
|
|
|
if not data.empty:
|
|
|
|
|
|
last_price = data["Close"].iloc[-1]
|
|
|
|
|
|
prices[ticker] = {
|
|
|
|
|
|
"price": round(last_price, 2),
|
|
|
|
|
|
"change_pct": round(
|
|
|
|
|
|
(last_price - data["Open"].iloc[0]) / data["Open"].iloc[0] * 100, 2
|
|
|
|
|
|
) if len(data) > 1 else 0,
|
|
|
|
|
|
"timestamp": datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"),
|
|
|
|
|
|
"category": category,
|
|
|
|
|
|
}
|
|
|
|
|
|
else:
|
|
|
|
|
|
prices[ticker] = {"price": None, "error": "No data"}
|
|
|
|
|
|
except Exception as exc: # noqa: BLE001
|
|
|
|
|
|
prices[ticker] = {"price": None, "error": str(exc)}
|
|
|
|
|
|
return prices
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def build_futures_context() -> str:
|
|
|
|
|
|
ctx = f"CURRENT FUTURES PRICES (as of {datetime.now().strftime('%Y-%m-%d %H:%M UTC')}):\n"
|
|
|
|
|
|
for ticker, info in fetch_current_futures_prices().items():
|
|
|
|
|
|
if info.get("price") is not None:
|
|
|
|
|
|
ctx += (
|
|
|
|
|
|
f"- {ticker} ({info['category']}): ${info['price']:.2f} "
|
|
|
|
|
|
f"({info['change_pct']:+.2f}% today)\n"
|
|
|
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
ctx += f"- {ticker}: unavailable ({info.get('error', 'unknown error')})\n"
|
|
|
|
|
|
return ctx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── DB helpers ─────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
2026-08-24 17:42:06 -04:00
|
|
|
|
def ensure_tables() -> None:
|
|
|
|
|
|
"""Idempotently create the news tables if missing.
|
|
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
Normally created by alembic 003_news + 005_news_items when the app
|
|
|
|
|
|
container starts, but this summarizer may boot before the app has run
|
|
|
|
|
|
migrations (compose only guarantees `db` is up, not that alembic has
|
|
|
|
|
|
run). Mirrors the scraper pipeline's own CREATE TABLE IF NOT EXISTS so
|
|
|
|
|
|
either start order is safe.
|
2026-08-24 17:42:06 -04:00
|
|
|
|
"""
|
|
|
|
|
|
ddl = """
|
|
|
|
|
|
CREATE TABLE IF NOT EXISTS articles (
|
|
|
|
|
|
id SERIAL PRIMARY KEY,
|
|
|
|
|
|
title TEXT,
|
|
|
|
|
|
url TEXT UNIQUE,
|
|
|
|
|
|
content TEXT,
|
|
|
|
|
|
domain TEXT,
|
|
|
|
|
|
timestamp TIMESTAMPTZ
|
|
|
|
|
|
);
|
|
|
|
|
|
CREATE TABLE IF NOT EXISTS article_summaries (
|
|
|
|
|
|
id SERIAL PRIMARY KEY,
|
|
|
|
|
|
summary_text TEXT NOT NULL,
|
|
|
|
|
|
batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
|
|
|
|
);
|
2026-08-27 23:17:45 -04:00
|
|
|
|
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS model TEXT;
|
2026-08-28 22:53:31 -04:00
|
|
|
|
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS kind TEXT;
|
2026-08-27 23:17:45 -04:00
|
|
|
|
CREATE TABLE IF NOT EXISTS news_items (
|
|
|
|
|
|
id SERIAL PRIMARY KEY,
|
|
|
|
|
|
summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE,
|
|
|
|
|
|
kind TEXT NOT NULL,
|
|
|
|
|
|
headline TEXT NOT NULL,
|
|
|
|
|
|
importance TEXT NOT NULL,
|
|
|
|
|
|
location_name TEXT,
|
|
|
|
|
|
lat DOUBLE PRECISION,
|
|
|
|
|
|
lon DOUBLE PRECISION,
|
|
|
|
|
|
location_confidence TEXT,
|
|
|
|
|
|
category TEXT,
|
|
|
|
|
|
url TEXT,
|
|
|
|
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
|
|
|
|
);
|
|
|
|
|
|
CREATE INDEX IF NOT EXISTS ix_news_items_kind_created
|
|
|
|
|
|
ON news_items (kind, created_at DESC);
|
|
|
|
|
|
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
|
|
|
|
|
|
ON news_items (lon, lat)
|
|
|
|
|
|
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL;
|
2026-11-13 21:47:30 -05:00
|
|
|
|
CREATE TABLE IF NOT EXISTS article_scores (
|
|
|
|
|
|
article_id INTEGER NOT NULL,
|
|
|
|
|
|
summary_id INTEGER,
|
|
|
|
|
|
score INTEGER NOT NULL,
|
|
|
|
|
|
category TEXT,
|
|
|
|
|
|
selected BOOLEAN NOT NULL,
|
|
|
|
|
|
model TEXT,
|
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
|
|
|
|
duplicate_of INTEGER,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
|
|
|
|
PRIMARY KEY (article_id, created_at)
|
|
|
|
|
|
);
|
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
|
|
|
|
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER;
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT;
|
|
|
|
|
|
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION;
|
|
|
|
|
|
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION;
|
|
|
|
|
|
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT;
|
2026-11-13 21:47:30 -05:00
|
|
|
|
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
|
|
|
|
|
|
ON article_scores (summary_id);
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox
|
|
|
|
|
|
ON article_scores (lon, lat)
|
|
|
|
|
|
WHERE lat IS NOT NULL AND lon IS NOT NULL;
|
2026-08-24 17:42:06 -04:00
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
cur = conn.cursor()
|
|
|
|
|
|
cur.execute(ddl)
|
|
|
|
|
|
conn.commit()
|
|
|
|
|
|
cur.close()
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
except Exception as exc: # noqa: BLE001
|
|
|
|
|
|
logger.error("Error ensuring news tables: %s", exc)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-28 22:53:31 -04:00
|
|
|
|
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
2026-11-13 21:56:46 -05:00
|
|
|
|
"""Fetch articles from the look-back window ``(now - window, now]``.
|
|
|
|
|
|
|
|
|
|
|
|
The upper bound is deliberate: future-dated rows (event listings, bad
|
|
|
|
|
|
scrape timestamps) must not be re-graded every interval. Rows with a NULL
|
|
|
|
|
|
timestamp have never matched the lower bound and still do not.
|
|
|
|
|
|
"""
|
2026-08-28 22:53:31 -04:00
|
|
|
|
mins = window_minutes if window_minutes is not None else effective_window_minutes()
|
2026-08-24 17:28:46 -04:00
|
|
|
|
query = """
|
2026-11-13 21:47:30 -05:00
|
|
|
|
SELECT id, title, content, url, domain
|
2026-08-24 17:28:46 -04:00
|
|
|
|
FROM articles
|
2026-08-28 20:53:32 -04:00
|
|
|
|
WHERE timestamp > NOW() - make_interval(mins => %s)
|
2026-11-13 21:56:46 -05:00
|
|
|
|
AND timestamp <= NOW()
|
2026-08-24 17:28:46 -04:00
|
|
|
|
AND content IS NOT NULL AND length(content) > 100
|
|
|
|
|
|
ORDER BY timestamp DESC;
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
cur = conn.cursor()
|
2026-08-28 22:53:31 -04:00
|
|
|
|
cur.execute(query, (mins,))
|
2026-08-24 17:28:46 -04:00
|
|
|
|
rows = cur.fetchall()
|
|
|
|
|
|
cur.close()
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
return [
|
2026-11-13 21:47:30 -05:00
|
|
|
|
{"id": r[0], "title": r[1], "content": r[2], "url": r[3], "domain": r[4]}
|
2026-08-24 17:28:46 -04:00
|
|
|
|
for r in rows
|
|
|
|
|
|
]
|
|
|
|
|
|
except Exception as exc: # noqa: BLE001
|
|
|
|
|
|
logger.error("Database error reading articles: %s", exc)
|
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-28 20:53:32 -04:00
|
|
|
|
def _already_summarized_this_interval() -> bool:
|
|
|
|
|
|
"""True when article_summaries already has a row in the last interval."""
|
2026-08-27 23:17:45 -04:00
|
|
|
|
if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1":
|
|
|
|
|
|
return False
|
|
|
|
|
|
query = (
|
|
|
|
|
|
"SELECT 1 FROM article_summaries "
|
2026-08-28 20:53:32 -04:00
|
|
|
|
"WHERE batch_timestamp >= NOW() - make_interval(secs => %s)"
|
2026-08-27 23:17:45 -04:00
|
|
|
|
)
|
|
|
|
|
|
try:
|
|
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
cur = conn.cursor()
|
2026-08-28 20:53:32 -04:00
|
|
|
|
cur.execute(query, (_summarize_interval_seconds(),))
|
2026-08-27 23:17:45 -04:00
|
|
|
|
row = cur.fetchone()
|
|
|
|
|
|
cur.close()
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
return row is not None
|
|
|
|
|
|
except Exception as exc: # noqa: BLE001
|
2026-08-28 20:53:32 -04:00
|
|
|
|
logger.error("Error checking interval idempotency: %s", exc)
|
2026-08-27 23:17:45 -04:00
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-08-28 22:53:31 -04:00
|
|
|
|
def _already_recapped_today() -> bool:
|
|
|
|
|
|
"""True when a daily_recap row already exists for the local calendar day."""
|
|
|
|
|
|
if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1":
|
|
|
|
|
|
return False
|
|
|
|
|
|
tz_name = (os.getenv("TZ") or "America/New_York").strip() or "America/New_York"
|
|
|
|
|
|
start = datetime.now(ZoneInfo(tz_name)).replace(
|
|
|
|
|
|
hour=0, minute=0, second=0, microsecond=0
|
|
|
|
|
|
)
|
|
|
|
|
|
query = (
|
|
|
|
|
|
"SELECT 1 FROM article_summaries "
|
|
|
|
|
|
"WHERE kind = 'daily_recap' AND batch_timestamp >= %s"
|
|
|
|
|
|
)
|
|
|
|
|
|
try:
|
|
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
cur = conn.cursor()
|
|
|
|
|
|
cur.execute(query, (start,))
|
|
|
|
|
|
row = cur.fetchone()
|
|
|
|
|
|
cur.close()
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
return row is not None
|
|
|
|
|
|
except Exception as exc: # noqa: BLE001
|
|
|
|
|
|
logger.error("Error checking recap idempotency: %s", exc)
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def save_batch(
|
2026-11-14 00:32:43 -05:00
|
|
|
|
summary_en: str,
|
|
|
|
|
|
model: str,
|
|
|
|
|
|
ticker: list,
|
|
|
|
|
|
map_items: list,
|
|
|
|
|
|
*,
|
|
|
|
|
|
kind: str = "interval",
|
|
|
|
|
|
articles: list | None = None,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
) -> int | None:
|
2026-11-14 00:32:43 -05:00
|
|
|
|
"""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 ``""``.
|
|
|
|
|
|
"""
|
2026-08-27 23:17:45 -04:00
|
|
|
|
ticker_rows = select_ticker(ticker or [])
|
|
|
|
|
|
map_rows = select_map(map_items or [])
|
|
|
|
|
|
text = (summary_en or "").strip()
|
|
|
|
|
|
if len(text) < 10 and not ticker_rows and not map_rows:
|
2026-08-24 17:28:46 -04:00
|
|
|
|
logger.info("Summary too short or empty. Skipping save.")
|
2026-11-13 21:47:30 -05:00
|
|
|
|
return None
|
2026-08-27 23:17:45 -04:00
|
|
|
|
insert_item = """
|
|
|
|
|
|
INSERT INTO news_items (
|
|
|
|
|
|
summary_id, kind, headline, importance, location_name,
|
|
|
|
|
|
lat, lon, location_confidence, category, url
|
|
|
|
|
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
|
|
|
|
|
"""
|
2026-08-24 17:28:46 -04:00
|
|
|
|
try:
|
|
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
cur = conn.cursor()
|
|
|
|
|
|
cur.execute(
|
2026-08-28 22:53:31 -04:00
|
|
|
|
"INSERT INTO article_summaries (summary_text, model, kind) VALUES (%s, %s, %s) RETURNING id",
|
|
|
|
|
|
(text, model, kind),
|
2026-08-24 17:28:46 -04:00
|
|
|
|
)
|
2026-08-27 23:17:45 -04:00
|
|
|
|
summary_id = cur.fetchone()[0]
|
|
|
|
|
|
for row in ticker_rows:
|
|
|
|
|
|
cur.execute(
|
|
|
|
|
|
insert_item,
|
|
|
|
|
|
(
|
|
|
|
|
|
summary_id,
|
|
|
|
|
|
"ticker",
|
|
|
|
|
|
row.get("headline"),
|
|
|
|
|
|
row.get("importance"),
|
|
|
|
|
|
row.get("location_name"),
|
|
|
|
|
|
None,
|
|
|
|
|
|
None,
|
|
|
|
|
|
None,
|
|
|
|
|
|
None,
|
2026-11-14 00:32:43 -05:00
|
|
|
|
article_url_for_row(row, articles),
|
2026-08-27 23:17:45 -04:00
|
|
|
|
),
|
|
|
|
|
|
)
|
|
|
|
|
|
for row in map_rows:
|
|
|
|
|
|
cur.execute(
|
|
|
|
|
|
insert_item,
|
|
|
|
|
|
(
|
|
|
|
|
|
summary_id,
|
|
|
|
|
|
"map",
|
|
|
|
|
|
row.get("headline"),
|
|
|
|
|
|
row.get("importance"),
|
|
|
|
|
|
row.get("location_name"),
|
|
|
|
|
|
row.get("lat"),
|
|
|
|
|
|
row.get("lon"),
|
|
|
|
|
|
row.get("location_confidence"),
|
|
|
|
|
|
row.get("category"),
|
2026-11-14 00:32:43 -05:00
|
|
|
|
article_url_for_row(row, articles),
|
2026-08-27 23:17:45 -04:00
|
|
|
|
),
|
|
|
|
|
|
)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
conn.commit()
|
2026-08-27 23:17:45 -04:00
|
|
|
|
logger.info(
|
2026-08-28 22:53:31 -04:00
|
|
|
|
"Master summary saved id=%s model=%s kind=%s ticker=%d map=%d",
|
|
|
|
|
|
summary_id, model, kind, len(ticker_rows), len(map_rows),
|
2026-08-27 23:17:45 -04:00
|
|
|
|
)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
cur.close()
|
|
|
|
|
|
conn.close()
|
2026-11-13 21:47:30 -05:00
|
|
|
|
return summary_id
|
2026-08-24 17:28:46 -04:00
|
|
|
|
except Exception as exc: # noqa: BLE001
|
2026-08-27 23:17:45 -04:00
|
|
|
|
logger.error("Error saving batch to DB: %s", exc)
|
2026-11-13 21:47:30 -05:00
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def persist_article_scores(
|
|
|
|
|
|
graded: list[dict], *, summary_id: int | None, model: str
|
|
|
|
|
|
) -> None:
|
|
|
|
|
|
"""Insert one article_scores row per graded article (selected true/false).
|
|
|
|
|
|
|
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 duplicates are written too, with ``selected=false`` and
|
|
|
|
|
|
``duplicate_of`` pointing at the surviving article id — the representative
|
|
|
|
|
|
carries the selection even when the copy itself scores above the bar.
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
Per-article geo (location_name/lat/lon/location_confidence) rides along
|
|
|
|
|
|
for the /api/news/blips layer; coords are re-validated and confidence
|
|
|
|
|
|
is restricted to the contract vocabulary at write time.
|
2026-11-13 21:47:30 -05:00
|
|
|
|
Best-effort: a failure here is logged and never aborts the run.
|
|
|
|
|
|
"""
|
|
|
|
|
|
rows = []
|
|
|
|
|
|
for block in graded or []:
|
|
|
|
|
|
article_id = block.get("article_id")
|
|
|
|
|
|
if article_id is None:
|
|
|
|
|
|
continue
|
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
|
|
|
|
duplicate_of = block.get("duplicate_of")
|
|
|
|
|
|
if not isinstance(duplicate_of, int):
|
|
|
|
|
|
duplicate_of = None
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
coords = clamp_coords(block.get("lat"), block.get("lon"))
|
|
|
|
|
|
lat, lon = coords if coords is not None else (None, None)
|
|
|
|
|
|
location_name = clean_location_name(block.get("location_name"))
|
|
|
|
|
|
confidence = block.get("location_confidence")
|
|
|
|
|
|
if lat is None or confidence not in GEO_CONFIDENCES:
|
|
|
|
|
|
confidence = None
|
2026-11-13 21:47:30 -05:00
|
|
|
|
rows.append(
|
|
|
|
|
|
(
|
|
|
|
|
|
article_id,
|
|
|
|
|
|
summary_id,
|
|
|
|
|
|
int(block.get("score") or 0),
|
|
|
|
|
|
block.get("category"),
|
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
|
|
|
|
bool(block.get("selected")) and duplicate_of is None,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
model,
|
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
|
|
|
|
duplicate_of,
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
location_name,
|
|
|
|
|
|
lat,
|
|
|
|
|
|
lon,
|
|
|
|
|
|
confidence,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
if not rows:
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
conn = psycopg2.connect(**DB_CONFIG)
|
|
|
|
|
|
cur = conn.cursor()
|
|
|
|
|
|
cur.executemany(
|
|
|
|
|
|
"INSERT INTO article_scores "
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
"(article_id, summary_id, score, category, selected, model, duplicate_of, "
|
|
|
|
|
|
" location_name, lat, lon, location_confidence) "
|
|
|
|
|
|
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
2026-11-13 21:47:30 -05:00
|
|
|
|
rows,
|
|
|
|
|
|
)
|
|
|
|
|
|
conn.commit()
|
|
|
|
|
|
cur.close()
|
|
|
|
|
|
conn.close()
|
|
|
|
|
|
logger.info(
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
"article_scores persisted rows=%d selected=%d duplicates=%d geo=%d summary_id=%s",
|
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
|
|
|
|
len(rows), sum(1 for r in rows if r[4]),
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
sum(1 for r in rows if r[6] is not None),
|
|
|
|
|
|
sum(1 for r in rows if r[8] is not None), summary_id,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
)
|
|
|
|
|
|
except Exception as exc: # noqa: BLE001
|
|
|
|
|
|
logger.error("Error persisting article_scores (run continues): %s", exc)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── Orchestration ──────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
def build_map_prompt(batch: list[dict]) -> str:
|
|
|
|
|
|
batch_text = "\n\n".join(
|
|
|
|
|
|
f"Title: {a['title']}\nSource: {a['domain']}\nURL: {a['url']}\nContent: {a['content'][:1500]}"
|
|
|
|
|
|
for a in batch
|
|
|
|
|
|
)
|
|
|
|
|
|
template = os.getenv("MAP_PROMPT", MAP_PROMPT_DEFAULT)
|
|
|
|
|
|
try:
|
2026-08-28 22:53:31 -04:00
|
|
|
|
return template.format(batch_text=batch_text)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
except KeyError:
|
2026-08-28 22:53:31 -04:00
|
|
|
|
return template
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
2026-08-28 22:53:31 -04:00
|
|
|
|
def build_master_prompt(final_input: str, recap: bool = False) -> str:
|
|
|
|
|
|
if recap:
|
|
|
|
|
|
template = os.getenv("RECAP_PROMPT", RECAP_PROMPT_DEFAULT)
|
|
|
|
|
|
else:
|
|
|
|
|
|
template = os.getenv("SUMMARY_PROMPT", SUMMARY_PROMPT_DEFAULT)
|
|
|
|
|
|
if "{final_input}" in template:
|
|
|
|
|
|
return template.replace("{final_input}", final_input)
|
|
|
|
|
|
return template
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def summarize_news() -> None:
|
2026-08-27 23:17:45 -04:00
|
|
|
|
"""Map-reduce summarize recent articles and store brief + ticker + map."""
|
2026-08-28 22:53:31 -04:00
|
|
|
|
recap = is_recap_run()
|
|
|
|
|
|
window = effective_window_minutes(recap=recap)
|
2026-08-24 17:42:06 -04:00
|
|
|
|
ensure_tables()
|
2026-08-28 22:53:31 -04:00
|
|
|
|
if recap:
|
|
|
|
|
|
if _already_recapped_today():
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
"Skipping recap: article_summaries already has daily_recap today "
|
|
|
|
|
|
"(set NEWS_SUMMARIZE_FORCE=1 to override)"
|
|
|
|
|
|
)
|
|
|
|
|
|
return
|
|
|
|
|
|
elif _already_summarized_this_interval():
|
2026-08-27 23:17:45 -04:00
|
|
|
|
logger.info(
|
2026-08-28 20:53:32 -04:00
|
|
|
|
"Skipping summarize: article_summaries already has a row in the last %ss "
|
|
|
|
|
|
"(set NEWS_SUMMARIZE_FORCE=1 to override)",
|
|
|
|
|
|
_summarize_interval_seconds(),
|
2026-08-27 23:17:45 -04:00
|
|
|
|
)
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
api_key = resolve_api_key()
|
|
|
|
|
|
model = resolve_model()
|
|
|
|
|
|
base_url = resolve_base_url()
|
|
|
|
|
|
if not api_key:
|
|
|
|
|
|
logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
2026-08-28 22:53:31 -04:00
|
|
|
|
articles = get_recent_news(window)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
if not articles:
|
2026-08-28 22:53:31 -04:00
|
|
|
|
logger.info("No new articles found in the last %s min.", window)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
return
|
|
|
|
|
|
|
2026-11-13 21:56:46 -05:00
|
|
|
|
min_score, top_n, fallback_top, fallback_min_score = selection_config()
|
2026-08-24 17:28:46 -04:00
|
|
|
|
logger.info(
|
2026-11-13 21:47:30 -05:00
|
|
|
|
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, "
|
2026-11-13 21:56:46 -05:00
|
|
|
|
"min_score=%d, top_n=%d, fallback_top=%d, fallback_min_score=%d)...",
|
2026-08-28 22:53:31 -04:00
|
|
|
|
len(articles), model, BATCH_SIZE, recap, window,
|
2026-11-13 21:56:46 -05:00
|
|
|
|
min_score, top_n, fallback_top, fallback_min_score,
|
2026-08-24 17:28:46 -04:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
graded: list[dict] = []
|
2026-08-24 17:28:46 -04:00
|
|
|
|
for i in range(0, len(articles), BATCH_SIZE):
|
|
|
|
|
|
batch = articles[i : i + BATCH_SIZE]
|
2026-11-13 21:47:30 -05:00
|
|
|
|
batch_index = i // BATCH_SIZE
|
2026-08-27 23:17:45 -04:00
|
|
|
|
logger.info(
|
|
|
|
|
|
"map batch %d/%d (%d articles)",
|
2026-11-13 21:47:30 -05:00
|
|
|
|
batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch),
|
2026-08-27 23:17:45 -04:00
|
|
|
|
)
|
2026-11-13 21:47:30 -05:00
|
|
|
|
response = call_llm(
|
2026-08-27 23:17:45 -04:00
|
|
|
|
build_map_prompt(batch),
|
|
|
|
|
|
api_key=api_key,
|
|
|
|
|
|
model=model,
|
|
|
|
|
|
base_url=base_url,
|
|
|
|
|
|
json_mode=False,
|
|
|
|
|
|
)
|
2026-11-13 21:47:30 -05:00
|
|
|
|
if not response:
|
|
|
|
|
|
continue
|
|
|
|
|
|
blocks, stats = parse_map_scores(
|
|
|
|
|
|
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
|
|
|
|
|
)
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
# Best-effort proximate geo: place-name-only blocks get offline
|
|
|
|
|
|
# gazetteer coords (confidence "approx"); misses stay coord-less.
|
|
|
|
|
|
for block in blocks:
|
|
|
|
|
|
fill_block_geo(block)
|
2026-11-13 21:47:30 -05:00
|
|
|
|
logger.info(
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d, geo=%d)",
|
2026-11-13 21:47:30 -05:00
|
|
|
|
batch_index + 1, stats["graded"], len(batch),
|
|
|
|
|
|
stats["fallback"], stats["unattributed"],
|
news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores:
- parse_map_scores extracts Location/Lat/Lon/Confidence per block
(clamp_coords-validated; Unknown -> no geo; never invent a place)
- place-name-only blocks resolve via a vendored offline GeoNames
gazetteer (cities15000 + admin1 + country->capital), confidence approx
- nullable location_name/lat/lon/location_confidence columns (alembic
014, single head; idempotent ensure_tables mirror) + partial bbox index
- GET /api/news/blips: frozen contract, dedup by article id (latest geo
wins), finite coords only, created_at DESC, bbox/since/limit, default
1000 max 5000, public read like /api/news/map
- critical/high map pins, ticker, grading thresholds, dedupe unchanged
Tests: 50 new summarizer geo tests (161 total), 18 new blips API
contract tests; alembic upgrade heads proven on fresh DBs both start
orders; forced batch on test DB yielded 10 non-critical blips with geo.
Card: t_bc15eb53
2026-11-19 22:50:59 -05:00
|
|
|
|
sum(1 for b in blocks if b.get("lat") is not None),
|
2026-11-13 21:47:30 -05:00
|
|
|
|
)
|
|
|
|
|
|
graded.extend(blocks)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
if not graded:
|
|
|
|
|
|
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
|
2026-08-24 17:28:46 -04:00
|
|
|
|
return
|
|
|
|
|
|
|
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
|
|
|
|
dedupe_enabled, dedupe_similarity = dedupe_config()
|
|
|
|
|
|
distinct, dedupe_stats = dedupe_blocks(
|
|
|
|
|
|
graded, similarity=dedupe_similarity, enabled=dedupe_enabled
|
|
|
|
|
|
)
|
|
|
|
|
|
duplicate_blocks = [record["block"] for record in dedupe_stats["duplicate_blocks"]]
|
|
|
|
|
|
for record in dedupe_stats["duplicate_blocks"]:
|
|
|
|
|
|
record["block"]["duplicate_of"] = record["duplicate_of"]
|
|
|
|
|
|
if dedupe_enabled:
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
"dedupe %d -> %d (kept %d, duplicates %d)",
|
|
|
|
|
|
dedupe_stats["input"], dedupe_stats["kept"],
|
|
|
|
|
|
dedupe_stats["kept"], dedupe_stats["duplicates"],
|
|
|
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.info("dedupe skipped (SUMMARY_DEDUPE=0)")
|
|
|
|
|
|
|
2026-11-13 21:47:30 -05:00
|
|
|
|
selected, used_fallback = select_graded(
|
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
|
|
|
|
distinct,
|
2026-11-13 21:56:46 -05:00
|
|
|
|
min_score=min_score,
|
|
|
|
|
|
top_n=top_n,
|
|
|
|
|
|
fallback_top=fallback_top,
|
|
|
|
|
|
fallback_min_score=fallback_min_score,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
)
|
|
|
|
|
|
selected_positions = {block["position"] for block in selected}
|
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
|
|
|
|
for block in distinct:
|
2026-11-13 21:47:30 -05:00
|
|
|
|
block["selected"] = block["position"] in selected_positions
|
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
|
|
|
|
for block in duplicate_blocks:
|
|
|
|
|
|
# The representative carries the selection; a wire copy never does.
|
|
|
|
|
|
block["selected"] = False
|
2026-11-13 21:47:30 -05:00
|
|
|
|
if used_fallback:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
"No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d "
|
2026-11-13 21:56:46 -05:00
|
|
|
|
"with score >= %d (max score %d)",
|
|
|
|
|
|
min_score, len(selected), fallback_min_score,
|
|
|
|
|
|
max(b["score"] for b in graded),
|
2026-11-13 21:47:30 -05:00
|
|
|
|
)
|
|
|
|
|
|
logger.info(
|
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
|
|
|
|
"selected %d/%d distinct articles for reduce (scores=%s)",
|
|
|
|
|
|
len(selected), len(distinct), [b["score"] for b in selected],
|
2026-11-13 21:47:30 -05:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
final_input = join_blocks(selected)
|
|
|
|
|
|
if not final_input.strip():
|
|
|
|
|
|
logger.warning(
|
2026-11-13 21:56:46 -05:00
|
|
|
|
"Selection is empty (min_score=%d, fallback_top=%d, "
|
|
|
|
|
|
"fallback_min_score=%d) — reduce gets empty DATA.",
|
|
|
|
|
|
min_score, fallback_top, fallback_min_score,
|
2026-11-13 21:47:30 -05:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-08-27 23:17:45 -04:00
|
|
|
|
master_raw = call_llm(
|
2026-08-28 22:53:31 -04:00
|
|
|
|
build_master_prompt(final_input, recap=recap),
|
2026-08-27 23:17:45 -04:00
|
|
|
|
api_key=api_key,
|
|
|
|
|
|
model=model,
|
|
|
|
|
|
base_url=base_url,
|
|
|
|
|
|
json_mode=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
if not master_raw:
|
|
|
|
|
|
logger.warning("Reduce phase returned empty — nothing to persist.")
|
|
|
|
|
|
return
|
|
|
|
|
|
parsed = parse_reduce_json(master_raw)
|
2026-11-14 00:32:43 -05:00
|
|
|
|
selected_articles = [
|
|
|
|
|
|
block["article"]
|
|
|
|
|
|
for block in selected
|
|
|
|
|
|
if isinstance(block.get("article"), dict)
|
|
|
|
|
|
]
|
2026-11-13 21:47:30 -05:00
|
|
|
|
summary_id = save_batch(
|
2026-08-28 22:53:31 -04:00
|
|
|
|
parsed["summary_en"],
|
|
|
|
|
|
model,
|
|
|
|
|
|
parsed["ticker"],
|
|
|
|
|
|
parsed["map_items"],
|
|
|
|
|
|
kind="daily_recap" if recap else "interval",
|
2026-11-14 00:32:43 -05:00
|
|
|
|
articles=selected_articles,
|
2026-08-28 22:53:31 -04:00
|
|
|
|
)
|
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
|
|
|
|
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
|
2026-08-24 17:28:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
summarize_news()
|