Spaces:
Sleeping

curium-intel / intel_feeds.py
mipwr-admin's picture
Sync from GitHub main — ERP priority, WMCA/Shropshire watchlist, network preserve-owners fix (a7395ea)
a87217c verified
Raw History Blame Contribute Delete
46.8 kB
""" Intel Feeds — free UK signal sources via RSS / public APIs. Adds four Tier-1 sources to the hunt without any new credentials: 1. **HR Magazine** — UK HR/L&D/transformation news (RSS) 2. **Personnel Today** — UK people/talent/employment news (RSS) 3. **RNS via Investegate** — London Stock Exchange regulatory announcements (RSS, free aggregation). Catches board changes, restructure announcements, M&A, programme launches at FTSE-listed companies before they hit mainstream news. 4. **Hansard** — UK Parliament transcripts (free API). Catches ministerial mentions of transformation programmes, procurement, specific named UK organisations — early signal for public-sector spend intent. All four persist into the existing `signals_news` table via collator.add_news_signal, with `source` set so we can filter / rank them downstream. No API keys required — all four are free public feeds. """ from __future__ import annotations import json import os import re import sqlite3 import time from datetime import date, datetime, timedelta from pathlib import Path from typing import Callable, Optional import feedparser import requests import yaml CONFIG_PATH = Path(__file__).parent / "config.yaml" DATABASE = "leads.db" # Companies / brands that are way outside Curium's ICP (200-10,000 employees, # UK/Ireland-led). Any item that mentions one of these gets dropped UNLESS it # also explicitly mentions a Curium target/client company. Meta-cap names # show up constantly in FT/City AM/BBC business feeds and waste digest space. # # Conservative principle: only include companies that are clearly outside # Curium's reach (>50k employees globally, US/Asia headquartered, or both). # When in doubt, leave it OUT of this list and let downstream scoring decide. OUT_OF_SCOPE_COMPANIES = [ # US Big Tech / mega-cap tech "Meta", "Facebook", "Instagram", "WhatsApp", "Threads", "Google", "Alphabet", "YouTube", "Apple", "Microsoft", "Amazon", "AWS", "Netflix", "Tesla", "SpaceX", "Nvidia", "Oracle", "Salesforce", "Adobe", "Intel Corp", # avoid matching "Intelligence" — use full term "IBM", "Cisco", "OpenAI", "Anthropic", "Uber", "Lyft", "Airbnb", "Stripe", # US Wall Street + asset managers "JPMorgan", "JP Morgan", "Bank of America", "Wells Fargo", "Citigroup", "Goldman Sachs", "Morgan Stanley", "BlackRock", "Vanguard", "Charles Schwab", # Global consumer mega-cap (US-headquartered) "McDonald", "Starbucks", "Coca-Cola", "PepsiCo", "Procter & Gamble", "P&G", "Nestle", "Nestlé", "Walmart", "ExxonMobil", "Exxon", "Chevron", # Asian mega-caps "Samsung", "Sony", "Toyota", "Honda", "Nissan", "Hyundai", "Tata Group", "Tata Motors", "Tata Consultancy", "LG Electronics", # Chinese tech / mega-cap "Alibaba", "Tencent", "WeChat", "Baidu", "ByteDance", "TikTok", "Xiaomi", "Huawei", "JD.com", # European industrial mega-caps "Siemens", "Schneider Electric", "Volkswagen Group", # group level only; "Volkswagen" UK ops stays in target_sectors ] def _detect_out_of_scope(text: str) -> Optional[str]: """Return the first out-of-scope company name found in `text`, else None.""" if not text: return None for name in OUT_OF_SCOPE_COMPANIES: pattern = r"\b" + re.escape(name) + r"\b" if re.search(pattern, text, re.IGNORECASE): return name return None # Keywords that indicate a Curium-relevant signal in news/RNS/Hansard items. # Used for cheap pre-filtering before persistence (fuller relevance scoring # happens downstream in collator/brain). RELEVANCE_KEYWORDS = [ # Transformation Delivery "transformation", "restructur", "reorganisation", "reorganization", "operating model", "programme", "PMO", "TMO", "change programme", "M&A integration", "merger", "acquisition", "carve-out", "carve out", "spin-off", "spin off", # Culture & Capability "culture change", "leadership change", "people strategy", "employee engagement", "wellbeing", "talent strategy", "L&D", "learning and development", "behaviour change", # Senior moves "appointed", "appoints", "resigns", "departs", "steps down", "succession", "interim ceo", "interim cfo", "new ceo", "new cfo", "chief people officer", "chief transformation", "chief operating", "chief executive", # Programme triggers "digital transformation", "AI strategy", "AI transformation", "cost reduction", "cost-cutting", "efficiency programme", ] def _config() -> dict: with open(CONFIG_PATH, "r") as f: return yaml.safe_load(f) def _curium_companies() -> list[str]: """All known UK companies of interest (target sectors + clients). Used for entity matching in news/RNS/Hansard text.""" cfg = _config() out: set[str] = set() for s in cfg.get("target_sectors", []) or []: for c in s.get("companies", []) or []: if c: out.add(c) for c in cfg.get("curium_clients", []) or []: n = c.get("name") if n: out.add(n) return sorted(out) def _is_relevant(text: str) -> bool: """Cheap keyword check before paying for downstream scoring.""" if not text: return False t = text.lower() return any(k in t for k in RELEVANCE_KEYWORDS) def _detect_company(text: str, candidates: list[str]) -> Optional[str]: """Match the first known company name appearing in `text`. Whole-word match where possible to avoid 'JCB' matching inside 'JCBank' etc.""" if not text: return None t = text for name in candidates: # Build a word-boundary regex; escape special chars in the name. pattern = r"\b" + re.escape(name) + r"\b" if re.search(pattern, t, re.IGNORECASE): return name return None def _date_within(pub_struct, days: int) -> bool: if not pub_struct: return True # if no date, don't reject — include and let downstream sort try: pub_dt = datetime(*pub_struct[:6]) return pub_dt >= datetime.now() - timedelta(days=days) except Exception: return True # ============================================================================= # RSS sources (HR Magazine, Personnel Today, Investegate RNS) # ============================================================================= # RSS feeds. Two categories: # - "hr_focused": entire feed is already on topic, no relevance filter # (would over-filter and drop relevant HR/L&D/culture items that don't # match generic business-transformation keywords). # - "business_news": general feeds where we apply the relevance keyword # filter to avoid noise. # All URLs verified working (HTTP 200, returning entries). RSS_FEEDS = { # HR / People focused — no filter "personnel_today": { "url": "https://www.personneltoday.com/feed/", "filter": False, }, "hr_director": { "url": "https://www.thehrdirector.com/feed/", "filter": False, }, # Business news — relevance-filtered (catches RNS-style company # announcements: board changes, restructures, M&A, programme launches) "ft_companies": { "url": "https://www.ft.com/companies?format=rss", "filter": True, }, "city_am": { "url": "https://www.cityam.com/feed/", "filter": True, }, "bbc_business": { "url": "https://feeds.bbci.co.uk/news/business/rss.xml", "filter": True, }, # UK public-sector / council intel — for the LGR opportunity. All # relevance-filtered because each feed covers more than just council # transformation (NAO audits all govt depts, LGC covers general # sector commentary, MHCLG publishes statistical bulletins as well # as policy). The LGR + programme_in_flight + restructure # classifiers do the heavy lifting on what's actually picked up. "nao_reports": { # National Audit Office — value-for-money reports including critical # reviews of council transformation programmes. Picks up "lessons # learned" reports that signal recovery opportunities. "url": "https://www.nao.org.uk/feed/", "filter": True, }, "lgc": { # Local Government Chronicle — UK council trade press. Covers exec # moves, programme launches, contract awards, LGR analysis. Less # syndicated to mainstream feeds so often surfaces signals first. "url": "https://www.lgcplus.com/feed", "filter": True, }, "mhclg": { # Ministry of Housing, Communities & Local Government (gov.uk). # LGR ministerial decisions, council intervention orders, funding # allocations (Levelling Up Fund, Towns Fund, devolution deals) # — the trigger events behind council transformation budgets. "url": "https://www.gov.uk/government/organisations/ministry-of-housing-communities-local-government.atom", "filter": True, }, } def fetch_rss(source_key: str, days: int = 7, max_items: int = 50, progress_cb: Optional[Callable[[str], None]] = None) -> list[dict]: """Generic RSS puller. Returns a list of {company, headline, reason, source, news_url, date} dicts ready for persist_news_items. `company` is left empty when no known UK company name matches the headline+summary — caller can still persist as a topical signal. Applies the relevance keyword filter only when the source is a general-business feed (where most items are off-topic). HR/people feeds skip the filter — the whole feed is on-topic by definition.""" cfg = RSS_FEEDS.get(source_key) if not cfg: if progress_cb: progress_cb(f"Unknown RSS source: {source_key}") return [] url = cfg["url"] apply_filter = cfg["filter"] if progress_cb: progress_cb(f"RSS: fetching {source_key}…") try: feed = feedparser.parse(url, request_headers={"User-Agent": "Mozilla/5.0 CuriumIntel"}) except Exception as e: if progress_cb: progress_cb(f"RSS {source_key} failed: {type(e).__name__}: {e}") return [] candidates = _curium_companies() out = [] skipped_out_of_scope = 0 for entry in (feed.entries or [])[:max_items]: title = (getattr(entry, "title", "") or "").strip() summary = (getattr(entry, "summary", "") or "").strip() link = (getattr(entry, "link", "") or "").strip() pub_struct = getattr(entry, "published_parsed", None) \ or getattr(entry, "updated_parsed", None) if not _date_within(pub_struct, days): continue body = f"{title}\n{summary}" if apply_filter and not _is_relevant(body): continue company = _detect_company(body, candidates) # ICP filter: drop items that mention only mega-cap / out-of-scope # companies. If the item also mentions a Curium target/client, keep # it (e.g. "Premier Foods partners with Microsoft on AI" is still # about Premier Foods). oos_hit = _detect_out_of_scope(body) if oos_hit and not company: skipped_out_of_scope += 1 continue date_str = "" if pub_struct: try: date_str = datetime(*pub_struct[:6]).isoformat(timespec="seconds") except Exception: pass out.append({ "company": company or "", "headline": title[:300], "reason": (summary[:500] if summary else title)[:500], "source": source_key, "news_url": link, "date": date_str, "trigger_type": _classify_trigger(body), }) if progress_cb: msg = f"RSS {source_key}: {len(out)} items kept" if skipped_out_of_scope: msg += f" ({skipped_out_of_scope} dropped — out of Curium ICP)" progress_cb(msg) return out def _classify_trigger(text: str) -> str: """Map a news headline+summary to one of our trigger_type values. Stricter than v1: 'leadership_change' now requires a *senior* role change (CEO/CFO/CHRO/COO/CTO/Chief X) — generic 'appointed' isn't enough on its own. 'transformation_programme' requires an actual programme verb (launches/announces/embarks/unveils), not just the word 'transformation' floating in passing. 'general' is the default drop-bucket for everything else; weekly_digest skips general items. """ t = (text or "").lower() # LGR (Local Government Reorganisation) + UK council crisis events — # checked first because these are tier-1 Curium opportunities with # their own specific signals. Every UK 2-tier county is in or moving # into LGR; the integration risk (operating model + ERP + people # change all at once) is exactly the Curium sweet spot. Section 114 # / Best Value / intervention notices flag councils in active crisis # — explicit forced-transformation moments. See # intel_assets/lgr_briefing.md. lgr_keywords = [ # LGR proper "local government reorganisation", "local government reorganization", "lgr proposal", "lgr submission", "lgr consultation", "lgr business case", "lgr programme", "unitary authority", "single unitary", "two unitaries", "council unification", "council merger", "districts merge", "joint authority", "shadow authority", "vesting day", "section 7 invitation", "minister approves council", "minister approves unitary", "ministerial direction council", "one oxfordshire", "one staffordshire", "one hampshire", "one kent", "one surrey", "one essex", "one sussex", "one suffolk", "one norfolk", "one devon", "one cheshire", "one warwickshire", "one leicestershire", # County-level merger/restructure markers "county council restructure", "district council merger", "transition lead", "lgr transition", "lgr readiness", # === Council-crisis signals (forced transformation moments) === # Section 114 = council declares effective bankruptcy. Each # one triggers a multi-year transformation programme. "section 114 notice", "s114 notice", "issues section 114", "issued section 114", "section 114 declaration", "effectively bankrupt", "declared bankrupt", # Best Value / statutory intervention "best value notice", "best value inspection", "statutory intervention", "commissioners appointed", "appoints commissioners", "appointed commissioners", "government intervention", "intervention notice", "best value duty", "special measures", "central government takeover", # NAO / PAC criticism of council programmes "nao critical", "nao report on", "nao investigation", "public accounts committee on council", "audit office report on council", # Major funding triggers (each kicks off a programme) "levelling up fund", "towns fund", "devolution deal", "devolution agreement", "uk shared prosperity", "long term plan for towns", ] if any(k in t for k in lgr_keywords): return "lgr_signal" # Programme IN FLIGHT — checked FIRST so mid-flight signals win # precedence over generic transformation_programme / leadership_change # buckets. These are often Curium's best entry point — client is past # strategy phase and needs delivery muscle. Includes distress, mid- # flight leadership churn, augmentation needs, recovery procurement, # phase transitions, and public-sector criticism of live programmes. in_flight_keywords = [ # Distress "programme delayed", "programme delay", "behind schedule", "over budget", "delivery issues", "implementation issues", "go-live delayed", "go-live postponed", "programme paused", "programme suspended", "programme reset", "programme reboot", "programme review", "programme recovery", "programme assurance", # Mid-flight leadership churn (ANY of these wins regardless of # whether the role is C-suite — a mid-flight director leaving # is a programme signal, not a leadership-change-only signal) "interim programme", "acting programme", "interim director of change", "acting director of change", "interim transformation", "acting transformation", "programme director departs", "programme director resigns", "transformation director departs", "transformation lead departs", "change director departs", "change director resigns", "mid-rollout", "mid-programme", "mid rollout", "mid programme", # Augmentation / additional partner signals "additional partner", "delivery partner", "augment the team", "augmenting the team", "scaling up the programme", "additional resources", "ramp up the programme", "expanded scope", "scope increase", "additional funding approved", # Procurement to bolster mid-flight programme "programme assurance", "programme recovery", "transformation assurance", "transformation support partner", "transformation support contract", "delivery assurance", # Phase markers (programme already running) "phase 2", "phase 3", "phase 4", "next phase", "go-live announced", # Public-sector criticism mid-programme "audit office criticism", "nao critical", "nao report", "public accounts committee", "highly critical", "lessons learned report", ] if any(k in t for k in in_flight_keywords): return "programme_in_flight" # Senior leadership change — only Chief / CEO / CFO / CHRO / COO / CTO # / VP-level moves count. Mid-level "appointed" doesn't. senior_role = any(role in t for role in [ "ceo", "chief executive", "cfo", "chief financial", "chro", "chief people", "chief human", "coo", "chief operating", "cto", "chief technology", "cio", "chief information", "chief transformation", "chief change", "chief commercial officer", "managing director", ]) move_verb = any(v in t for v in ["appointed", "appoints", "resigns", "departs", "steps down", "succession", "named", "joins as", "to become", "promoted to"]) if senior_role and move_verb: return "leadership_change" # Restructure — explicit if any(k in t for k in ["restructur", "reorganis", "reorganiz", "redundancies", "redundancy programme", "layoff", "lay off", "operating model", "cost-out programme", "efficiency programme"]): return "restructure" # M&A activity — completed/announced deals (not rumour) if any(k in t for k in ["merger", "acquisition", "acquired", "acquires", "buyout", "carve-out", "carve out", "spin-off", "spin off", "divest", "demerger", "post-merger"]): return "ma_activity" # Transformation programme — fresh launch, needs an action verb if any(k in t for k in ["transformation programme", "launches transformation", "kicks off transformation", "embarks on transformation", "announces transformation", "unveils transformation", "digital transformation programme", "new operating model", "embark on a programme", "erp rollout", "erp implementation", "sap rollout", "sap implementation", "workday rollout", "workday implementation", "ifs implementation", "oracle rollout"]): return "transformation_programme" # Culture & Capability — at-scale, with action verb if any(k in t for k in ["culture programme", "leadership programme", "leadership development", "talent strategy", "behaviour change programme", "succession planning", "wellbeing strategy"]): return "culture_capability" # Contract / framework awards (mainly relevant when a transformation # consultancy wins a UK gov framework — early signal that we should # try to get on the next one) if any(k in t for k in ["awarded contract", "wins contract", "framework agreement", "framework award", "framework contract", "framework deal", "signs deal worth", "signs contract worth"]): return "contract_award" # "wins ... contract" with up to 30 chars between (e.g. monetary value) if re.search(r"\bwins\b[^.\n]{0,30}\bcontract\b", t): return "contract_award" return "general" # ============================================================================= # Hansard (UK Parliament transcripts) # ============================================================================= HANSARD_API = "https://hansard-api.parliament.uk" # Search terms tailored to surface UK public-sector transformation/change # spend intent. Each generates one search call — keep the list small. HANSARD_SEARCH_TERMS = [ "transformation programme", "operating model", "change management programme", "council restructuring", "civil service reform", "public sector transformation", ] def fetch_hansard(days: int = 14, per_term: int = 10, progress_cb: Optional[Callable[[str], None]] = None) -> list[dict]: """Search Hansard for recent contributions mentioning our search terms. Returns the same shape as fetch_rss so the persist layer is shared.""" out = [] cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d") candidates = _curium_companies() for term in HANSARD_SEARCH_TERMS: if progress_cb: progress_cb(f"Hansard: '{term}'…") try: r = requests.get( f"{HANSARD_API}/search/contributions/Spoken.json", params={ "queryParameters.searchTerm": term, "queryParameters.startDate": cutoff, "queryParameters.take": per_term, "queryParameters.orderBy": "Date", }, timeout=15, ) r.raise_for_status() data = r.json() except Exception as e: if progress_cb: progress_cb(f"Hansard '{term}' failed: {type(e).__name__}: {e}") continue results = (data or {}).get("Results") or [] for hit in results[:per_term]: title = (hit.get("Title") or "").strip() text = (hit.get("ContributionText") or hit.get("Value") or "").strip() # DebateSection can be a dict or a string depending on the # endpoint version; only treat it as a dict if it actually is one. url = hit.get("ContributionUrl") or "" ds = hit.get("DebateSection") if not url and isinstance(ds, dict): url = ds.get("DebateSectionUrl") or "" if not url: # Build link to the parliament.uk hansard page if possible debate_id = hit.get("DebateSectionExtId") or hit.get("DebateSectionId") if debate_id: url = f"https://hansard.parliament.uk/{debate_id}" speaker = (hit.get("MemberName") or "").strip() sit_date = (hit.get("SittingDate") or "").strip() body = f"{title} {text}" company = _detect_company(body, candidates) headline = (title or text)[:300] if speaker: headline = f"{speaker}: {headline}" out.append({ "company": company or "", "headline": headline, "reason": (f"Hansard mention of '{term}'. " f"Speaker: {speaker or 'Unknown'}. " f"Excerpt: {text[:300]}").strip()[:500], "source": "hansard", "news_url": url, "date": sit_date, "trigger_type": _classify_trigger(body), }) time.sleep(0.4) # gentle on Hansard API if progress_cb: progress_cb(f"Hansard: {len(out)} mentions across {len(HANSARD_SEARCH_TERMS)} terms") return out # ============================================================================= # Find a Tender Service (UK above-threshold tenders >£138k) # ============================================================================= FTS_SEARCH_API = "https://www.find-tender.service.gov.uk/api/1.0/ocdsReleasePackages" # Title/description keywords that indicate a transformation / consulting # tender. The FTS OCDS feed doesn't reliably populate CPV classifications # at the item level, so we filter on title/description instead. FTS_TENDER_KEYWORDS = [ "transformation", "operating model", "change management", "change programme", "consultancy", "consulting", "advisory", "leadership development", "talent", "L&D", "learning and development", "PMO", "TMO", "programme management", "project management", "organisational design", "organizational design", "operating model", "M&A integration", "merger integration", "post-merger", "restructur", "reorganisation", "reorganization", "culture change", "wellbeing", "engagement strategy", "digital transformation", "AI strategy", "people strategy", "workforce strategy", "modernisation", "modernization", ] def _matches_tender_keywords(text: str) -> list[str]: """Return matching keywords (used to surface why a tender was kept).""" if not text: return [] t = text.lower() return [k for k in FTS_TENDER_KEYWORDS if k.lower() in t][:5] # ============================================================================= # LINKEDIN SIGNALS — Tier 1 (Google-indexed public posts, ToS-safe) # ============================================================================= # # LinkedIn public posts are crawled and indexed by Google. We run targeted # Google searches (site:linkedin.com) to surface: # - Job-change / appointment announcements at priority councils & clients # - Posts about LGR, transformation pain, ERP from target-org employees # - Thought-leadership signals from tracked stakeholders # - Competitor mentions ("excited to work with [firm]…") # # No LinkedIn account is touched. No scraping. No API. This uses the same # web_search tool as the LGR deep-research passes — fully ToS-compliant. # Google's index lags a few days and misses private/connection-only posts, # but catches every public post — which is where the appointment announcements # and pain-signal posts live. _LI_SEARCH_QUERIES = [ # Appointment / job-change announcements at priority LGR councils 'site:linkedin.com "county council" ("delighted to join" OR "excited to announce" OR "pleased to share" OR "new role") ("transformation" OR "programme director" OR "LGR" OR "reorganisation")', # LGR pain signals from council employees 'site:linkedin.com ("local government reorganisation" OR "LGR") ("transformation" OR "operating model" OR "ERP" OR "programme") ("challenging" OR "complex" OR "lessons learned" OR "preparing for")', # Hertfordshire CC — priority target 'site:linkedin.com "Hertfordshire County Council" ("transformation" OR "LGR" OR "reorganisation" OR "unitary") -job -jobs', # Lancashire CC — Nick's warm route 'site:linkedin.com "Lancashire County Council" ("transformation" OR "LGR" OR "programme director") -job -jobs', # Essex CC — Peter Shakespear warm route 'site:linkedin.com "Essex County Council" ("transformation" OR "LGR" OR "programme director") -job -jobs', # Competitor displacement signals — across all councils 'site:linkedin.com ("county council" OR "local authority") ("working with" OR "partnering with" OR "delighted to support") ("transformation" OR "LGR") ("consultancy" OR "consulting" OR "advisory")', # Curium's ICP sectors — ERP / operating model pain 'site:linkedin.com ("ERP transformation" OR "SAP implementation" OR "Oracle implementation") ("challenging" OR "behind schedule" OR "lessons learned" OR "programme recovery") ("county council" OR "public sector" OR "local government")', # Tracked stakeholders by name — surface any recent posts 'site:linkedin.com/in ("Sandy Walkington" OR "Steve Jarvis" OR "Angie Ridgwell" OR "Mark Wynn" OR "Monica Fogarty") "LGR" OR "reorganisation" OR "transformation"', ] # Signal scoring by post type _LI_TRIGGER_MAP = { "delighted to join": ("appointment", 85), "excited to announce": ("appointment", 85), "pleased to share": ("appointment", 80), "new role": ("appointment", 75), "lgr": ("lgr_signal", 80), "local government reorganisation": ("lgr_signal", 80), "programme recovery": ("programme_in_flight", 80), "behind schedule": ("programme_in_flight", 75), "lessons learned": ("programme_in_flight", 65), "working with": ("competitor_signal", 70), "partnering with": ("competitor_signal", 70), "challenging": ("programme_in_flight", 60), "erp transformation": ("erp_signal", 70), } def fetch_linkedin_signals( max_searches: int = 8, progress_cb: Optional[Callable[[str], None]] = None, ) -> list[dict]: """Run targeted Google site:linkedin.com searches to surface public post signals from priority councils and tracked stakeholders. Returns the same {company, headline, reason, source, news_url, date} shape as fetch_rss so persist_news_items can handle them without modification. Safe: uses only web_search (Google index). No LinkedIn account touched, no scraping, no API calls to LinkedIn. Public posts only.""" try: import anthropic as _anthropic except ImportError: if progress_cb: progress_cb("LinkedIn signals: anthropic SDK not available — skipping") return [] api_key = os.environ.get("ANTHROPIC_API_KEY", "").strip() if not api_key: if progress_cb: progress_cb("LinkedIn signals: ANTHROPIC_API_KEY not set — skipping") return [] if progress_cb: progress_cb("LinkedIn signals: scanning public posts via Google…") client = _anthropic.Anthropic(api_key=api_key) items: list[dict] = [] queries = _LI_SEARCH_QUERIES[:max_searches] for i, query in enumerate(queries): if progress_cb: progress_cb(f" LinkedIn signals [{i+1}/{len(queries)}]…") try: response = client.messages.create( model="claude-haiku-4-5", max_tokens=1200, tools=[{ "type": "web_search_20250305", "name": "web_search", "max_uses": 1, }], messages=[{ "role": "user", "content": ( f"Search LinkedIn public posts using this query and return the " f"top 3 most relevant results. For each result return ONLY: " f"1) the post URL, 2) the author name and organisation if visible, " f"3) a one-sentence summary of the post's signal value for a UK " f"transformation consultancy. Be concise.\n\nQuery: {query}" ), }], ) # Extract text response text = "" for block in response.content: if hasattr(block, "text"): text += block.text if not text.strip(): continue # Parse results — look for URLs and surrounding context # Each result is a loose paragraph; we extract company/person signals paragraphs = [p.strip() for p in text.split("\n") if p.strip()] for para in paragraphs: para_l = para.lower() # Detect trigger type and score trigger_type = "linkedin_signal" score = 60 for phrase, (tt, sc) in _LI_TRIGGER_MAP.items(): if phrase in para_l: trigger_type = tt score = sc break # Extract URL if present url_match = re.search(r"https?://[^\s\)\"']+linkedin[^\s\)\"']+", para) url = url_match.group(0) if url_match else "" # Extract company name — look for known council/org mentions company = "[LinkedIn Signal]" candidates = _curium_companies() for c in candidates: if c.lower() in para_l: company = c break # Also try generic council detection if company == "[LinkedIn Signal]": council_match = re.search( r"([A-Z][a-z]+(?: [A-Z][a-z]+)*)\s+(?:County|City|Borough|District|Metropolitan)\s+Council", para ) if council_match: company = council_match.group(0) # Only persist if we have a real signal sentence (not just a URL line) if len(para) < 30 or not any(c.isalpha() for c in para): continue items.append({ "company": company, "headline": f"[LinkedIn] {para[:200]}", "reason": f"Public LinkedIn post signal (query {i+1}/{len(queries)}): {query[:100]}", "source": "linkedin_signals", "news_url": url, "date": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), "trigger_type": trigger_type, "score": score, }) except Exception as e: if progress_cb: progress_cb(f" LinkedIn signals query {i+1} error: {e}") continue time.sleep(1) # courteous pacing between searches if progress_cb: progress_cb(f"LinkedIn signals: {len(items)} signals found") return items def fetch_fts_tenders(days: int = 30, max_pages: int = 5, progress_cb: Optional[Callable[[str], None]] = None) -> list[dict]: """Query Find a Tender Service for recent UK tenders. Filters by: (a) title/description containing transformation/consulting keywords, OR (b) buyer matching a Curium target sector or client list. Returns dicts shaped for the existing add_tender_signal helper.""" cutoff = (datetime.now() - timedelta(days=days)).isoformat() + "Z" out = [] cursor = None pages = 0 target_buyers = {b.lower() for b in _curium_companies()} if progress_cb: progress_cb(f"FTS: querying since {cutoff[:10]} (kw + buyer match)…") while pages < max_pages: params = { "updatedFrom": cutoff, "limit": 100, } if cursor: params["cursor"] = cursor try: r = requests.get(FTS_SEARCH_API, params=params, timeout=30) r.raise_for_status() data = r.json() except Exception as e: if progress_cb: progress_cb(f"FTS request failed: {type(e).__name__}: {e}") break releases = data.get("releases") or [] if not releases: break for rel in releases: try: tender = rel.get("tender") or {} buyer_obj = (rel.get("buyer") or {}) buyer = (buyer_obj.get("name") or "").strip() if not buyer: continue title = (tender.get("title") or "").strip() description = (tender.get("description") or "").strip() body = f"{title} {description}" # Match either by keyword OR by known target/client buyer kw_hits = _matches_tender_keywords(body) buyer_hit = buyer.lower() in target_buyers or any( tb in buyer.lower() for tb in target_buyers if len(tb) > 4 ) if not (kw_hits or buyer_hit): continue # Pull value — can be in tender.value or in awards value_obj = (tender.get("value") or {}) value_amount = value_obj.get("amount") or 0 if not value_amount: awards = rel.get("awards") or [] for aw in awards: v = (aw.get("value") or {}).get("amount") if v: value_amount = v break tender_period = tender.get("tenderPeriod") or {} deadline = tender_period.get("endDate") or "" ocid = rel.get("ocid", "") tender_url = ( f"https://www.find-tender.service.gov.uk/Notice/{ocid}" if ocid else "" ) days_to = None if deadline: try: dl = datetime.fromisoformat(deadline.replace("Z", "+00:00")) days_to = (dl - datetime.now(dl.tzinfo)).days except Exception: pass matched = kw_hits or [f"buyer-match: {buyer}"] out.append({ "buyer": buyer, "title": title or description[:120], "value": int(value_amount) if value_amount else 0, "deadline": deadline, "days_to_deadline": days_to, "is_urgent": (days_to is not None and days_to <= 14), "matched_keywords": matched, "url": tender_url, "source": "fts", }) except Exception: continue # Pagination cursor links = data.get("links") or {} next_url = links.get("next") if not next_url: break from urllib.parse import urlparse, parse_qs qs = parse_qs(urlparse(next_url).query) cursor = (qs.get("cursor") or [None])[0] if not cursor: break pages += 1 time.sleep(0.3) if progress_cb: progress_cb(f"FTS: {len(out)} matching tenders found") return out # ============================================================================= # Persistence — write into existing signals_* tables via collator # ============================================================================= def persist_news_items(items: list[dict]) -> int: if not items: return 0 try: from collator import add_news_signal except ImportError: return 0 n = 0 for it in items: company = (it.get("company") or "").strip() if not company: # Topical-only items (no company match) get persisted under a # synthetic "[Industry]" company so they still surface in # sector-scoped queries. We DON'T want to lose them entirely # because briefings + radar pages aggregate by topic too. company = "[Industry News]" try: add_news_signal( company_name=company, headline=it.get("headline", "")[:300], reason=it.get("reason", "")[:500], trigger_type=it.get("trigger_type", "general"), urgency="medium", news_url=it.get("news_url", ""), source=it.get("source", "rss"), news_score=60, ) n += 1 except Exception: continue return n def persist_tender_items(items: list[dict]) -> int: if not items: return 0 try: from collator import add_tender_signal except ImportError: return 0 n = 0 for it in items: try: add_tender_signal( company_name=it.get("buyer", ""), title=it.get("title", ""), value=it.get("value", 0), deadline=it.get("deadline", ""), days_to_deadline=it.get("days_to_deadline"), is_urgent=it.get("is_urgent", False), matched_keywords=", ".join(str(k) for k in (it.get("matched_keywords") or [])), tender_url=it.get("url", ""), ) n += 1 except Exception: continue return n # ============================================================================= # Public entrypoints — called from hunter.py # ============================================================================= _ERP_SYSTEMS = [ "SAP S/4HANA", "SAP ECC", "Oracle Fusion", "Oracle Cloud", "Microsoft Dynamics", "Unit4", "Workday", "Agresso", "Civica", "Capita One", "MHR iTrent", "Cornerstone", ] _ERP_QUERIES = [ # End-of-life ERP at councils — highest signal '("county council" OR "city council" OR "borough council") ' '("SAP ECC" OR "Oracle EBS" OR "Agresso" OR "Unit4") ' '("upgrade" OR "replacement" OR "migration" OR "new system" OR "go-live" OR "tender")', # Procurement notices for ERP/HR/finance systems '("county council" OR "unitary authority") ' '("ERP" OR "finance system" OR "HR system" OR "payroll system") ' '("tender" OR "procurement" OR "framework" OR "contract award") ' f'after:{date.today().strftime("%Y-%m-%d")}', # LGR + ERP overlap — Curium sweet spot '("local government reorganisation" OR "LGR" OR "unitary") ' '("ERP" OR "SAP" OR "Oracle" OR "Microsoft Dynamics" OR "systems consolidation")', ] def fetch_erp_signals( progress_cb: Optional[Callable[[str], None]] = None, ) -> list[dict]: """Weekly ERP technographic pass — finds councils with live ERP procurement, migration, or end-of-life system signals. These are direct buying indicators: a council on SAP ECC (EOL 2027) or Agresso facing LGR has an unavoidable systems transformation in their near-term future. Curium's sweet spot.""" try: import anthropic as _anthropic except ImportError: return [] api_key = os.environ.get("ANTHROPIC_API_KEY", "").strip() if not api_key: return [] if progress_cb: progress_cb("ERP signals: scanning council tech landscape…") client = _anthropic.Anthropic(api_key=api_key) items: list[dict] = [] for i, query in enumerate(_ERP_QUERIES): if progress_cb: progress_cb(f" ERP signals [{i+1}/{len(_ERP_QUERIES)}]…") try: response = client.messages.create( model="claude-haiku-4-5", max_tokens=1000, tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 1}], messages=[{ "role": "user", "content": ( f"Search: {query}\n\nReturn top 3 most relevant results as JSON array. " f"Each: {{\"title\":\"...\",\"url\":\"...\",\"council\":\"...\"," f"\"erp_system\":\"...\",\"signal\":\"1 sentence signal summary\"}}\n" f"Return [] if nothing relevant found." ), }], ) text = "".join(b.text for b in response.content if hasattr(b, "text")).strip() m = re.search(r"\[.*\]", text, re.S) if not m: continue hits = json.loads(m.group(0)) or [] for h in hits: council = h.get("council") or "[Industry News]" erp = h.get("erp_system", "") signal_summary = h.get("signal", "") items.append({ "company": council, "headline": f"[ERP Signal{(' — ' + erp) if erp else ''}] {h.get('title','')[:200]}", "reason": signal_summary or f"ERP/systems signal: {query[:80]}", "source": "erp_signals", "news_url": h.get("url", ""), "date": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), "trigger_type": "erp_signal", "score": 75, }) except Exception as e: if progress_cb: progress_cb(f" ERP signals query {i+1} error: {e}") time.sleep(1) if progress_cb: progress_cb(f"ERP signals: {len(items)} found") return items def run_news_feeds(days: int = 7, progress_cb: Optional[Callable[[str], None]] = None) -> dict: """Run all RSS + Hansard + LinkedIn + ERP signals sources and persist. Returns counts.""" counts = {} total = 0 for src in RSS_FEEDS.keys(): items = fetch_rss(src, days=days, progress_cb=progress_cb) counts[src] = len(items) total += persist_news_items(items) items = fetch_hansard(days=max(days, 14), progress_cb=progress_cb) counts["hansard"] = len(items) total += persist_news_items(items) # LinkedIn public post signals via Google index (ToS-safe, no scraping) li_items = fetch_linkedin_signals(progress_cb=progress_cb) counts["linkedin_signals"] = len(li_items) total += persist_news_items(li_items) # ERP technographic pass — council systems signals erp_items = fetch_erp_signals(progress_cb=progress_cb) counts["erp_signals"] = len(erp_items) total += persist_news_items(erp_items) counts["persisted_total"] = total return counts def run_fts(days: int = 30, progress_cb: Optional[Callable[[str], None]] = None) -> dict: """Run FTS pull + persist.""" items = fetch_fts_tenders(days=days, progress_cb=progress_cb) n = persist_tender_items(items) return {"found": len(items), "persisted": n}
"""
Intel Feeds — free UK signal sources via RSS / public APIs.
Adds four Tier-1 sources to the hunt without any new credentials:
1. **HR Magazine** — UK HR/L&D/transformation news (RSS)
2. **Personnel Today** — UK people/talent/employment news (RSS)
3. **RNS via Investegate** — London Stock Exchange regulatory
announcements (RSS, free aggregation). Catches board changes,
restructure announcements, M&A, programme launches at FTSE-listed
companies before they hit mainstream news.
4. **Hansard** — UK Parliament transcripts (free API). Catches
ministerial mentions of transformation programmes, procurement,
specific named UK organisations — early signal for public-sector
spend intent.
All four persist into the existing `signals_news` table via
collator.add_news_signal, with `source` set so we can filter / rank
them downstream.
No API keys required — all four are free public feeds.
"""
from __future__ import annotations
import json
import os
import re
import sqlite3
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Callable, Optional
import feedparser
import requests
import yaml
CONFIG_PATH = Path(__file__).parent / "config.yaml"
DATABASE = "leads.db"
# Companies / brands that are way outside Curium's ICP (200-10,000 employees,
# UK/Ireland-led). Any item that mentions one of these gets dropped UNLESS it
# also explicitly mentions a Curium target/client company. Meta-cap names
# show up constantly in FT/City AM/BBC business feeds and waste digest space.
#
# Conservative principle: only include companies that are clearly outside
# Curium's reach (>50k employees globally, US/Asia headquartered, or both).
# When in doubt, leave it OUT of this list and let downstream scoring decide.
OUT_OF_SCOPE_COMPANIES = [
# US Big Tech / mega-cap tech
"Meta", "Facebook", "Instagram", "WhatsApp", "Threads",
"Google", "Alphabet", "YouTube",
"Apple",
"Microsoft",
"Amazon", "AWS",
"Netflix",
"Tesla", "SpaceX",
"Nvidia",
"Oracle",
"Salesforce",
"Adobe",
"Intel Corp", # avoid matching "Intelligence" — use full term
"IBM",
"Cisco",
"OpenAI", "Anthropic",
"Uber", "Lyft", "Airbnb",
"Stripe",
# US Wall Street + asset managers
"JPMorgan", "JP Morgan",
"Bank of America",
"Wells Fargo",
"Citigroup",
"Goldman Sachs",
"Morgan Stanley",
"BlackRock",
"Vanguard",
"Charles Schwab",
# Global consumer mega-cap (US-headquartered)
"McDonald", "Starbucks",
"Coca-Cola", "PepsiCo",
"Procter & Gamble", "P&G",
"Nestle", "Nestlé",
"Walmart",
"ExxonMobil", "Exxon", "Chevron",
# Asian mega-caps
"Samsung",
"Sony",
"Toyota", "Honda", "Nissan", "Hyundai",
"Tata Group", "Tata Motors", "Tata Consultancy",
"LG Electronics",
# Chinese tech / mega-cap
"Alibaba",
"Tencent", "WeChat",
"Baidu",
"ByteDance", "TikTok",
"Xiaomi",
"Huawei",
"JD.com",
# European industrial mega-caps