ii-assistent/hunter/monitor.py

227 lines
8.3 KiB
Python

import hashlib
import logging
import time
from datetime import datetime, timedelta, timezone
from urllib.parse import urlsplit, urlunsplit
import feedparser
from .db import connect, now
from .network import fetch, public_url, text
logger = logging.getLogger(__name__)
CATEGORY_WORDS = {
"HealthTech": ("health", "medical", "clinical", "hospital"),
"FinTech": ("fintech", "bank", "payment", "finance"),
"Smart Home": ("smart home", "home automation", "matter "),
"Robotics": ("robot", "autonomous"),
"Telecom": ("telecom", "5g", "6g", "wireless", "broadband"),
"EdTech": ("education", "learning platform", "school"),
"SpaceTech": ("nasa", "space", "satellite"),
"AI": ("artificial intelligence", " ai ", "machine learning", "llm"),
}
def category_for(value, fallback):
lowered = f" {value.lower()} "
return next(
(key for key, words in CATEGORY_WORDS.items() if any(w in lowered for w in words)), fallback
)
def canonical_url(url):
parts = urlsplit(url)
if (
parts.scheme not in ("http", "https")
or not parts.hostname
or parts.username
or parts.password
):
raise ValueError("invalid_link")
# Retain query: some publishers use an article id in it.
return urlunsplit(
(parts.scheme.lower(), parts.netloc.lower(), parts.path or "/", parts.query, "")
)
def parse_feed(body):
parsed = feedparser.parse(body)
if not parsed.entries:
raise ValueError("empty_feed")
result = []
for entry in parsed.entries[:30]:
try:
url = canonical_url(entry.get("link", ""))
except ValueError:
continue
published = entry.get("published_parsed") or entry.get("updated_parsed")
date = (
datetime(*published[:6], tzinfo=timezone.utc).isoformat(timespec="seconds")
if published
else None
)
title = text(entry.get("title", ""), 300)
if title:
result.append(
dict(
title=title,
summary=text(entry.get("summary", ""), 700),
url=url,
published=date,
)
)
return result
def acquire_run(path):
with connect(path) as db:
db.execute("BEGIN IMMEDIATE")
stale = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat(timespec="seconds")
db.execute(
"UPDATE runs SET status='interrupted', finished=? WHERE status='running' AND started<?",
(now(), stale),
)
if db.execute("SELECT 1 FROM runs WHERE status='running'").fetchone():
return None
return db.execute(
"INSERT INTO runs(started,status) VALUES(?,'running')", (now(),)
).lastrowid
def collect(path, fetcher=fetch, analyze=True):
run_id = acquire_run(path)
if run_id is None:
return {"status": "busy", "added": 0}
added = 0
errors = 0
try:
with connect(path) as db:
sources = db.execute("SELECT * FROM sources WHERE enabled=1").fetchall()
for source in sources:
count = 0
try:
entries = parse_feed(fetcher(source["url"]))
with connect(path) as db:
for entry in entries:
if "hnrss.org" in source["url"]:
entry["summary"] = "" # Feed metadata is not an article summary.
# Verify article address before storing a clickable link.
try:
public_url(entry["url"])
except (ValueError, OSError):
continue
cursor = db.execute(
"INSERT OR IGNORE INTO signals(source_id,title,summary,url,published,collected,category,country) VALUES(?,?,?,?,?,?,?,?)",
(
source["id"],
entry["title"],
entry["summary"],
entry["url"],
entry["published"],
now(),
category_for(
entry["title"] + " " + entry["summary"], source["category"]
),
source["country"],
),
)
count += cursor.rowcount
db.execute(
"UPDATE sources SET status='ok', updated=?, count=(SELECT count(*) FROM signals WHERE source_id=?) WHERE id=?",
(now(), source["id"], source["id"]),
)
status = "ok"
except Exception as exc:
# Only exception type in logs: no response bodies/credentials.
logger.warning("Source %s: %s", source["id"], type(exc).__name__)
errors += 1
status = "error"
with connect(path) as db:
db.execute("UPDATE sources SET status='error' WHERE id=?", (source["id"],))
with connect(path) as db:
db.execute(
"INSERT INTO logs(created,name,status,added) VALUES(?,?,?,?)",
(now(), source["name"], status, count),
)
added += count
collect_companies(path, fetcher)
if analyze:
from .analysis import analyze_materials
try:
analyze_materials(path)
except Exception as exc:
logger.warning("Analysis: %s", type(exc).__name__)
errors += 1
with connect(path) as db:
db.execute(
"INSERT INTO logs(created,name,status) VALUES(?,?,?)",
(now(), "analysis", "error"),
)
status = "partial" if errors else "ok"
except Exception:
status = "error"
raise
finally:
with connect(path) as db:
db.execute(
"UPDATE runs SET status=?, finished=?, added=? WHERE id=?",
(locals().get("status", "error"), now(), added, run_id),
)
return {"status": status, "added": added}
def collect_companies(path, fetcher=fetch):
with connect(path) as db:
companies = db.execute("SELECT * FROM companies").fetchall()
for company in companies:
try:
content = text(fetcher(company["url"]), 12000)
if not content:
raise ValueError("empty_page")
with connect(path) as db:
previous = company["snapshot"]
if (
previous
and hashlib.sha256(previous.encode()).digest()
!= hashlib.sha256(content.encode()).digest()
):
db.execute(
"INSERT INTO changes(company_id,previous,current,created) VALUES(?,?,?,?)",
(company["id"], previous, content, now()),
)
db.execute(
"UPDATE companies SET snapshot=?, updated=?, status='ok' WHERE id=?",
(content, now(), company["id"]),
)
except Exception as exc:
logger.warning("Company %s: %s", company["id"], type(exc).__name__)
with connect(path) as db:
db.execute("UPDATE companies SET status='error' WHERE id=?", (company["id"],))
def scheduler(path, once=False):
while True:
with connect(path) as db:
hours = int(db.execute("SELECT value FROM settings WHERE key='interval'").fetchone()[0])
last = db.execute(
"SELECT finished FROM runs WHERE finished IS NOT NULL ORDER BY id DESC LIMIT 1"
).fetchone()
if not last or datetime.fromisoformat(last[0]) + timedelta(hours=hours) <= datetime.now(
timezone.utc
):
collect(path)
if once:
return
time.sleep(30)
if __name__ == "__main__":
import os
import sys
from .db import init_db
path = os.getenv("DATABASE_PATH", "data/hunter.sqlite3")
init_db(path)
scheduler(path, "--once" in sys.argv)