Add news pipeline: hourly scraper + Gemini summarizer in compose
Some checks failed
build-and-deploy / build (push) Failing after 4s

Vendor the newsPipeline scraper + summarizer into the repo and wire them into
docker-compose against the EXISTING osint-db (no second Postgres), replacing
the upstream k8s CronJobs with in-compose wall-clock loops (:00 scrape, :05
summarize).

- news/scraper: vendored Scrapy project (257 RSS feeds) + hourly loop
  scheduler (run_news_scraper.py)
- news/summerizer: vendored Gemini map-reduce summarizer, cleaned:
  * fix broken google-genai response handling (_extract_text, defensive)
  * fix malformed INSERT/GRANT query in save_summary_to_db
  * OSINT-neutral default MAP_PROMPT; futures/markets language gated behind
    INCLUDE_FUTURES=0 (yfinance lazy-imported)
  * env-configurable model, batch size, lookback window
  + hourly loop scheduler (run_news_summarizer.py, :05)
- alembic 003_news: idempotent articles + article_summaries tables
- API: GET /api/news and GET /api/news/summaries (+ models, schemas)
- tests/test_api_news.py: 5 DB-backed contract tests (all pass vs real PG)
- docs/news.md + .env.example updates

Both services run under the `ingest` compose profile (matching the
ingester/camera-scraper pattern) and build arm64 on the Pi via the existing
Forgejo CI workflow. telebot left out of scope (reserved env only).
This commit is contained in:
Sirius DevOps 2026-08-24 17:28:46 -04:00
commit 91f436390b
27 changed files with 1772 additions and 2 deletions

View file

View file

@ -0,0 +1,12 @@
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class NewsscraperItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass

View file

@ -0,0 +1,113 @@
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class NewsscraperSpiderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, or item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Request or item objects.
pass
async def process_start(self, start):
# Called with an async iterator over the spider start() method or the
# matching method of an earlier spider middleware.
async for item_or_request in start:
yield item_or_request
def spider_opened(self, spider):
spider.logger.info("Spider opened: %s" % spider.name)
class NewsscraperDownloaderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info("Spider opened: %s" % spider.name)
class ProxyMiddleware:
def __init__(self, proxy_url):
self.proxy_url = proxy_url
@classmethod
def from_crawler(cls, crawler):
return cls(proxy_url=crawler.settings.get('PROXY_URL'))
def process_request(self, request, spider):
# Only attach the proxy if PROXY_URL was successfully built
if self.proxy_url:
request.meta['proxy'] = self.proxy_url

View file

@ -0,0 +1,92 @@
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import logging
import psycopg2
import os
from scrapy.exceptions import DropItem
class PostgresPipeline:
def __init__(self, db_config):
# 1. Store the config
self.db_config = db_config
# 2. Initialize the set here so it exists when process_item is called
self.seen_urls = set()
@classmethod
def from_crawler(cls, crawler):
db_config = {
'host': crawler.settings.get('DB_HOST'),
'database': crawler.settings.get('DB_NAME'),
'user': crawler.settings.get('DB_USER'),
'password': crawler.settings.get('DB_PASSWORD'),
}
return cls(db_config=db_config)
def open_spider(self, spider):
# Connect using environment variables
self.connection = psycopg2.connect(
host=os.getenv('DB_HOST'),
database=os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
port=os.getenv('DB_PORT', '5432')
)
self.cur = self.connection.cursor()
# Create table if it doesn't exist
self.cur.execute("""
CREATE TABLE IF NOT EXISTS articles (
id SERIAL PRIMARY KEY,
title TEXT,
url TEXT UNIQUE,
content TEXT,
domain TEXT,
timestamp TIMESTAMPTZ
)
""")
self.connection.commit()
def process_item(self, item, spider):
if item ['url'] in self.seen_urls:
raise DropItem()
try:
self.cur.execute("""
INSERT INTO articles (title, url, content, domain, timestamp)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (url) DO NOTHING
""", (
item['title'],
item['url'],
item['text'],
item['domain'],
item['timestamp']
))
if self.cur.rowcount == 0:
e = DropItem("Duplicate URL (database conflict)")
e.log_level = logging.DEBUG
raise e
self.connection.commit()
return item
except Exception as e:
spider.logger.error(f"Error saving to Postgres: {e}")
self.connection.rollback()
raise
def close_spider(self, spider):
self.cur.close()
self.connection.close()
from itemadapter import ItemAdapter
class NewsscraperPipeline:
def process_item(self, item, spider):
return item

View file

@ -0,0 +1,94 @@
import os
from dotenv import load_dotenv
load_dotenv()
PROXY_USER = os.getenv('PROXY_USER', '').strip()
PROXY_PASS = os.getenv('PROXY_PASS', '').strip()
PROXY_ENDPOINT = os.getenv('PROXY_ENDPOINT', '').strip()
def get_proxy_url():
if not PROXY_ENDPOINT:
return None
endpoint = PROXY_ENDPOINT.replace('http://', '').replace('https://','')
if PROXY_USER and PROXY_PASS:
return f"http://{PROXY_USER}:{PROXY_PASS}@{endpoint}"
else:
return f"http://{endpoint}"
PROXY_URL = get_proxy_url()
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
}
BOT_NAME = "newsScraper"
SPIDER_MODULES = ["newsScraper.spiders"]
NEWSPIDER_MODULE = "newsScraper.spiders"
ADDONS = {}
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = os.getenv('USER_AGENT', "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Concurrency and throttling settings
CONCURRENT_REQUESTS = os.getenv('CONCURRENT_REQUESTS', '100').strip()
CONCURRENT_REQUESTS_PER_DOMAIN = 2
DOWNLOAD_DELAY = 3
REACTOR_THREADPOOL_MAXSIZE = 100
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
RETRY_ENABLED = True
DOWNLOAD_TIMEOUT = 60
AJAXCRAWL_ENABLED = False
AUTO_THROTTLE_ENABLED = True
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0
DNSCACHE_ENABLED = True
DNSCACHE_SIZE = 20000
DNS_TIMEOUT = 20
DNS_RESOLVER = 'scrapy.resolver.CachingThreadedResolver'
DEPTH_LIMIT = os.getenv('DEPTH_LIMIT', 1)
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEEDS = {
'data/hourly_news.jsonl':{
'format': 'jsonlines',
'encoding': 'utf8',
'overwrite': True,
}
}
FEED_EXPORT_ENCODING = "utf-8"
ITEM_PIPELINES = {
'newsScraper.pipelines.PostgresPipeline': 300,
}
# Database Config (These should be in your .env / K8s Secrets)
DB_HOST = os.getenv('DB_HOST', 'postgres-service')
DB_NAME = os.getenv('DB_NAME', 'news_db')
DB_USER = os.getenv('DB_USER', 'admin')
DB_PASSWORD = os.getenv('DB_PASSWORD')
db_config = {
'host': DB_HOST,
'database': DB_NAME,
'user': DB_USER,
'password': DB_PASSWORD,
'port': 5432 # Default postgres port
}

View file

@ -0,0 +1,4 @@
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.

View file

@ -0,0 +1,50 @@
import scrapy
from scrapy.spiders import XMLFeedSpider
from urllib.parse import urlparse
import datetime
import re
class NewsRSSSpider(XMLFeedSpider):
name = "articles"
iterator = 'xml'
itertag = 'item' # Standard RSS tag for an article
namespaces = [
('dc', 'http://purl.org/dc/elements/1.1/'),
('content', 'http://purl.org/rss/1.0/modules/content/'),
('media', 'http://search.yahoo.com/mrss/')
]
def __init__(self, filename='urls.txt', *args, **kwargs):
super(NewsRSSSpider, self).__init__(*args, **kwargs)
with open(filename, 'r') as f:
# We filter for RSS feeds only here
self.start_urls = [line.strip() for line in f if '/rss' in line or '/feed' in line]
def parse_node(self, response, node):
"""This runs for every <item> found in the RSS XML"""
title = node.xpath('title/text()').get()
link = node.xpath('link/text()').get()
pub_date = node.xpath('pubDate/text()').get()
# We now yield a Request to the actual article to get the full text
# Since these are RSS links, they are usually 'clean' HTML
if link:
yield scrapy.Request(link, callback=self.parse_article, meta={'title': title, 'date': pub_date})
def parse_article(self, response):
title = response.meta.get('title')
# Greedy search for the main text body
article_text = response.xpath('//article//p/text() | //main//p/text() | //div[contains(@class, "body")]//p/text()').getall()
pure_text = " ".join(article_text)
pure_text = re.sub(r'\s+', ' ', pure_text).strip()
if len(pure_text) > 300:
yield {
'title': title,
'url': response.url,
'text': pure_text,
'domain': urlparse(response.url).netloc,
'timestamp': datetime.datetime.now().isoformat()
}