feat: continuous news scrape + 15-min analyst, expand urls.txt
Scraper loops with NEWS_SCRAPE_INTERVAL_S (default 10s after each crawl). Summarizer runs every NEWS_SUMMARIZE_INTERVAL_S (default 900) over the last 15 minutes of articles. Feed list replaced from the k8s scrapy-urls configmap (334 sources).
This commit is contained in:
parent
eb883f0801
commit
8643153954
11 changed files with 434 additions and 376 deletions
|
|
@ -1,14 +1,10 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Scheduler loop for the news summarizer — hourly summarize at minute :05.
|
||||
"""Scheduler loop for the news summarizer — every NEWS_SUMMARIZE_INTERVAL_S.
|
||||
|
||||
Replaces the k8s CronJob (`5 * * * *`) with an in-compose loop. Runs once on
|
||||
boot (catches up on any articles scraped since the last summary), then fires
|
||||
at each :NEWS_SUMMARIZE_MINUTE wall-clock boundary.
|
||||
|
||||
The loop is serial, so a slow LLM pass never overlaps the next run.
|
||||
Default 900s (15 minutes). Serial: a slow LLM pass never overlaps the next.
|
||||
|
||||
Env (all optional, 12-factor):
|
||||
NEWS_SUMMARIZE_MINUTE minute of the hour to fire (default 5)
|
||||
NEWS_SUMMARIZE_INTERVAL_S seconds between runs (default 900)
|
||||
NEWS_SUMMARIZE_RUN_ON_START "1" to summarize once immediately on boot (default 1)
|
||||
NOUS_API_KEY optional in env; Keys UI / api_keys also works
|
||||
"""
|
||||
|
|
@ -25,17 +21,10 @@ import time
|
|||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("news.summarizer.scheduler")
|
||||
|
||||
MINUTE = int(os.getenv("NEWS_SUMMARIZE_MINUTE", "5"))
|
||||
INTERVAL_S = max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900")))
|
||||
RUN_ON_START = os.getenv("NEWS_SUMMARIZE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
def seconds_until_next(minute: int) -> float:
|
||||
"""Seconds until the next occurrence of ``minute`` past the hour (local time)."""
|
||||
now = datetime.datetime.now()
|
||||
nxt = now.replace(minute=minute, second=0, microsecond=0) + datetime.timedelta(hours=1)
|
||||
return (nxt - now).total_seconds()
|
||||
|
||||
|
||||
def run_summarize() -> None:
|
||||
logger.info("summarize starting at %s", datetime.datetime.now().isoformat(timespec="seconds"))
|
||||
try:
|
||||
|
|
@ -51,15 +40,14 @@ def main() -> None:
|
|||
"NOUS_API_KEY unset in env — will read api_keys on each run; idle if both empty"
|
||||
)
|
||||
logger.info(
|
||||
"news summarizer loop starting (minute=%s, run_on_start=%s)",
|
||||
MINUTE, RUN_ON_START,
|
||||
"news summarizer loop starting (interval_s=%s, run_on_start=%s)",
|
||||
INTERVAL_S, RUN_ON_START,
|
||||
)
|
||||
if RUN_ON_START:
|
||||
run_summarize()
|
||||
while True:
|
||||
delay = seconds_until_next(MINUTE)
|
||||
logger.info("next summarize at :%02d (in %.0fs)", MINUTE, delay)
|
||||
time.sleep(delay)
|
||||
logger.info("next summarize in %ss", INTERVAL_S)
|
||||
time.sleep(INTERVAL_S)
|
||||
run_summarize()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python3
|
||||
"""News summarizer — Nous map-reduce of scraped articles into brief/ticker/map.
|
||||
|
||||
Reads articles scraped within the last hour from the shared `articles` table,
|
||||
Reads articles scraped within the last SUMMARY_WINDOW_MINUTES from the shared `articles` table,
|
||||
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
|
||||
|
|
@ -15,11 +15,8 @@ of each summarize_news() — env wins, else api_keys / app_settings:
|
|||
NOUS_BASE_URL default https://inference-api.nousresearch.com/v1
|
||||
SUMMARY_MODEL default Hermes-4.3-36B (else app_settings)
|
||||
BATCH_SIZE articles per map-phase batch (default 50)
|
||||
SUMMARY_WINDOW_HOURS look-back window in hours (default 1)
|
||||
OSINT_USER_AGENT default osint-dashboard-news-summarizer
|
||||
MAP_PROMPT override map-phase prompt (uses {batch_text})
|
||||
SUMMARY_PROMPT override reduce-phase prompt (uses {final_input})
|
||||
NEWS_SUMMARIZE_FORCE "1" to ignore the current-UTC-hour idempotency skip
|
||||
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
|
||||
|
|
@ -54,7 +51,23 @@ DB_CONFIG = {
|
|||
DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
|
||||
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
||||
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
||||
SUMMARY_WINDOW_HOURS = int(os.getenv("SUMMARY_WINDOW_HOURS", "1"))
|
||||
|
||||
|
||||
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")))
|
||||
|
||||
|
||||
SUMMARY_WINDOW_MINUTES = _summary_window_minutes()
|
||||
INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes")
|
||||
|
||||
# Only touched when INCLUDE_FUTURES=1 (legacy markets coupling, OSINT-off).
|
||||
|
|
@ -282,18 +295,18 @@ def ensure_tables() -> None:
|
|||
|
||||
|
||||
def get_recent_news() -> list[dict]:
|
||||
"""Fetch articles from the last SUMMARY_WINDOW_HOURS (content > 100 chars)."""
|
||||
"""Fetch articles from the last SUMMARY_WINDOW_MINUTES (content > 100 chars)."""
|
||||
query = """
|
||||
SELECT title, content, url, domain
|
||||
FROM articles
|
||||
WHERE timestamp > NOW() - make_interval(hours => %s)
|
||||
WHERE timestamp > NOW() - make_interval(mins => %s)
|
||||
AND content IS NOT NULL AND length(content) > 100
|
||||
ORDER BY timestamp DESC;
|
||||
"""
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
cur = conn.cursor()
|
||||
cur.execute(query, (SUMMARY_WINDOW_HOURS,))
|
||||
cur.execute(query, (SUMMARY_WINDOW_MINUTES,))
|
||||
rows = cur.fetchall()
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
|
@ -306,24 +319,24 @@ def get_recent_news() -> list[dict]:
|
|||
return []
|
||||
|
||||
|
||||
def _already_summarized_this_hour() -> bool:
|
||||
"""True when article_summaries already has a row for the current UTC hour."""
|
||||
def _already_summarized_this_interval() -> bool:
|
||||
"""True when article_summaries already has a row in the last interval."""
|
||||
if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1":
|
||||
return False
|
||||
query = (
|
||||
"SELECT 1 FROM article_summaries "
|
||||
"WHERE batch_timestamp >= date_trunc('hour', NOW() AT TIME ZONE 'utc')"
|
||||
"WHERE batch_timestamp >= NOW() - make_interval(secs => %s)"
|
||||
)
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
cur = conn.cursor()
|
||||
cur.execute(query)
|
||||
cur.execute(query, (_summarize_interval_seconds(),))
|
||||
row = cur.fetchone()
|
||||
cur.close()
|
||||
conn.close()
|
||||
return row is not None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Error checking hourly idempotency: %s", exc)
|
||||
logger.error("Error checking interval idempotency: %s", exc)
|
||||
return False
|
||||
|
||||
|
||||
|
|
@ -419,10 +432,11 @@ def build_master_prompt(final_input: str) -> str:
|
|||
def summarize_news() -> None:
|
||||
"""Map-reduce summarize recent articles and store brief + ticker + map."""
|
||||
ensure_tables()
|
||||
if _already_summarized_this_hour():
|
||||
if _already_summarized_this_interval():
|
||||
logger.info(
|
||||
"Skipping summarize: article_summaries already has a row this UTC hour "
|
||||
"(set NEWS_SUMMARIZE_FORCE=1 to override)"
|
||||
"Skipping summarize: article_summaries already has a row in the last %ss "
|
||||
"(set NEWS_SUMMARIZE_FORCE=1 to override)",
|
||||
_summarize_interval_seconds(),
|
||||
)
|
||||
return
|
||||
|
||||
|
|
@ -435,7 +449,7 @@ def summarize_news() -> None:
|
|||
|
||||
articles = get_recent_news()
|
||||
if not articles:
|
||||
logger.info("No new articles found in the last %sh.", SUMMARY_WINDOW_HOURS)
|
||||
logger.info("No new articles found in the last %s min.", SUMMARY_WINDOW_MINUTES)
|
||||
return
|
||||
|
||||
logger.info(
|
||||
|
|
|
|||
Loading…
Reference in a new issue