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