feat: 23:00 daily news recap; prompts drop futures

Summarizer still runs the 15-min analyst, plus a 24h breaking-news recap
at 23:00 America/New_York. HUD pins kind=daily_recap. Prompts ignore
futures/market tape.
This commit is contained in:
Sirius DevOps 2026-08-28 22:53:31 -04:00
commit 49ee5fe7a3
16 changed files with 431 additions and 75 deletions

View file

@ -16,13 +16,10 @@ of each summarize_news() — env wins, else api_keys / app_settings:
SUMMARY_MODEL default Hermes-4.3-36B (else app_settings)
BATCH_SIZE articles per map-phase batch (default 50)
SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set)
NEWS_SUMMARIZE_FORCE "1" to ignore the interval idempotency skip
INCLUDE_FUTURES "1" to prepend live futures prices (default 0)
The futures/markets coupling from the original pipeline is gated behind
INCLUDE_FUTURES and OFF by default — it is irrelevant to the OSINT dashboard
and pulled yfinance into the image. Re-enable by installing yfinance and
setting INCLUDE_FUTURES=1.
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
"""
from __future__ import annotations
@ -30,6 +27,7 @@ from __future__ import annotations
import logging
import os
from datetime import datetime
from zoneinfo import ZoneInfo
import psycopg2
@ -67,6 +65,18 @@ def _summarize_interval_seconds() -> int:
return max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900")))
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()
SUMMARY_WINDOW_MINUTES = _summary_window_minutes()
INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes")
@ -84,6 +94,8 @@ FUTURES_TICKERS = {
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.
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.
Write every field in English. Translate if the article is not English.
For EACH article in the batch:
@ -91,7 +103,7 @@ For EACH article in the batch:
2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
5. OSINT signal: if the article describes an event with geopolitical, security, military, economic, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
5. 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."
6. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none.
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
@ -117,10 +129,12 @@ Articles in this batch:
"""
SUMMARY_PROMPT_DEFAULT = """\
CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO MAJOR GEOPOLITICAL/TECH/MILITARY/ECONOMIC/IMPACTFUL EVENTS OR UNUSUAL STORIES, set summary_en to exactly: "No qualifying impactful or unusual events in the recent hourly news data." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING.
CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO BREAKING IMPORTANT NEWS, set summary_en to exactly: "No qualifying breaking news in the recent news data." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING.
All text in English.
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures, commodity prices, and routine market data — do not treat price ticks as news.
Demand a single JSON object (no markdown fences) with this exact shape:
{
@ -131,7 +145,32 @@ Demand a single JSON object (no markdown fences) with this exact shape:
ticker: only critical and high, max 12, ≤140 chars, no markdown.
map_items: only critical and high 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 brief for an operator HUD.
summary_en: English markdown brief of breaking important news for an operator HUD.
DATA:
{final_input}
"""
RECAP_PROMPT_DEFAULT = """\
You are writing a daily recap of the last 24 hours of news for an OSINT operator HUD.
CRITICAL INSTRUCTION: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO BREAKING IMPORTANT NEWS, set summary_en to exactly: "No qualifying breaking news in the last 24 hours." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING.
All text in English.
Focus on breaking important news from the last 24 hours (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures, commodity prices, and routine market data — do not treat price ticks as news.
Demand a single JSON object (no markdown fences) with this exact shape:
{
"summary_en": "English markdown daily recap or the no-qualifying-events sentence",
"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": ""}]
}
ticker: only critical and high, max 12, ≤140 chars, no markdown.
map_items: only critical and high 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 of breaking important news.
DATA:
{final_input}
@ -263,6 +302,7 @@ def ensure_tables() -> None:
batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS model TEXT;
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS kind TEXT;
CREATE TABLE IF NOT EXISTS news_items (
id SERIAL PRIMARY KEY,
summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE,
@ -294,8 +334,9 @@ def ensure_tables() -> None:
logger.error("Error ensuring news tables: %s", exc)
def get_recent_news() -> list[dict]:
"""Fetch articles from the last SUMMARY_WINDOW_MINUTES (content > 100 chars)."""
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
"""Fetch articles from the look-back window (content > 100 chars)."""
mins = window_minutes if window_minutes is not None else effective_window_minutes()
query = """
SELECT title, content, url, domain
FROM articles
@ -306,7 +347,7 @@ def get_recent_news() -> list[dict]:
try:
conn = psycopg2.connect(**DB_CONFIG)
cur = conn.cursor()
cur.execute(query, (SUMMARY_WINDOW_MINUTES,))
cur.execute(query, (mins,))
rows = cur.fetchall()
cur.close()
conn.close()
@ -340,7 +381,34 @@ def _already_summarized_this_interval() -> bool:
return False
def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> None:
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(
summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval"
) -> None:
"""Insert the master brief plus flagged ticker/map rows."""
ticker_rows = select_ticker(ticker or [])
map_rows = select_map(map_items or [])
@ -358,8 +426,8 @@ def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> No
conn = psycopg2.connect(**DB_CONFIG)
cur = conn.cursor()
cur.execute(
"INSERT INTO article_summaries (summary_text, model) VALUES (%s, %s) RETURNING id",
(text, model),
"INSERT INTO article_summaries (summary_text, model, kind) VALUES (%s, %s, %s) RETURNING id",
(text, model, kind),
)
summary_id = cur.fetchone()[0]
for row in ticker_rows:
@ -396,8 +464,8 @@ def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> No
)
conn.commit()
logger.info(
"Master summary saved id=%s model=%s ticker=%d map=%d",
summary_id, model, len(ticker_rows), len(map_rows),
"Master summary saved id=%s model=%s kind=%s ticker=%d map=%d",
summary_id, model, kind, len(ticker_rows), len(map_rows),
)
cur.close()
conn.close()
@ -413,26 +481,35 @@ def build_map_prompt(batch: list[dict]) -> str:
for a in batch
)
template = os.getenv("MAP_PROMPT", MAP_PROMPT_DEFAULT)
prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else ""
try:
return prefix + template.format(batch_text=batch_text)
return template.format(batch_text=batch_text)
except KeyError:
return prefix + template
return template
def build_master_prompt(final_input: str) -> str:
template = os.getenv("SUMMARY_PROMPT", SUMMARY_PROMPT_DEFAULT)
prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else ""
try:
return prefix + template.format(final_input=final_input)
except KeyError:
return prefix + template
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
def summarize_news() -> None:
"""Map-reduce summarize recent articles and store brief + ticker + map."""
recap = is_recap_run()
window = effective_window_minutes(recap=recap)
ensure_tables()
if _already_summarized_this_interval():
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():
logger.info(
"Skipping summarize: article_summaries already has a row in the last %ss "
"(set NEWS_SUMMARIZE_FORCE=1 to override)",
@ -447,14 +524,14 @@ def summarize_news() -> None:
logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run")
return
articles = get_recent_news()
articles = get_recent_news(window)
if not articles:
logger.info("No new articles found in the last %s min.", SUMMARY_WINDOW_MINUTES)
logger.info("No new articles found in the last %s min.", window)
return
logger.info(
"Processing %d articles with %s (batch_size=%d, futures=%s)...",
len(articles), model, BATCH_SIZE, INCLUDE_FUTURES,
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s)...",
len(articles), model, BATCH_SIZE, recap, window,
)
partial_summaries: list[str] = []
@ -481,7 +558,7 @@ def summarize_news() -> None:
logger.info("reduce phase over %d partial summaries", len(partial_summaries))
master_raw = call_llm(
build_master_prompt(final_input),
build_master_prompt(final_input, recap=recap),
api_key=api_key,
model=model,
base_url=base_url,
@ -491,7 +568,13 @@ def summarize_news() -> None:
logger.warning("Reduce phase returned empty — nothing to persist.")
return
parsed = parse_reduce_json(master_raw)
save_batch(parsed["summary_en"], model, parsed["ticker"], parsed["map_items"])
save_batch(
parsed["summary_en"],
model,
parsed["ticker"],
parsed["map_items"],
kind="daily_recap" if recap else "interval",
)
if __name__ == "__main__":