Spaces:
Sleeping
Sleeping
Sync from GitHub main β ERP priority, WMCA/Shropshire watchlist, network preserve-owners fix (a7395ea)
a87217c verified Download scripts/realtime_alerts.py from mipwr-admin/curium-intel: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/scripts/realtime_alerts.py
- Command line
-
hf download hf://spaces/mipwr-admin/curium-intel/scripts/realtime_alerts.py
-
curl -L -o realtime_alerts.py https://huggingface.co/spaces/mipwr-admin/curium-intel/resolve/main/scripts/realtime_alerts.py
13 kB
| """ | |
| Real-time tier-1 signal monitor. | |
| Runs every 2 hours via GitHub Actions cron. Searches for the highest- | |
| priority signals that shouldn't wait until Monday: | |
| - S114 / effective bankruptcy notices at UK councils | |
| - Government unitary structure decisions (LGR outcomes) | |
| - Competitor wins / partnership announcements at target councils | |
| - Senior appointments at priority LGR councils | |
| On a hit, fires an immediate email to ADMIN_EMAIL (and optionally all | |
| enabled team_emails). Uses a state file in HF Dataset to avoid | |
| re-alerting on the same event. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from datetime import date, datetime | |
| from pathlib import Path | |
| REPO_ROOT = Path(__file__).resolve().parent.parent | |
| sys.path.insert(0, str(REPO_ROOT)) | |
| try: | |
| from dotenv import load_dotenv | |
| load_dotenv(REPO_ROOT / ".env", override=False) | |
| except ImportError: | |
| pass | |
| import mailer | |
| from anthropic import Anthropic | |
| # --------------------------------------------------------------------------- | |
| # Watchlist β queries run every 2 hours | |
| # --------------------------------------------------------------------------- | |
| WATCHLIST = [ | |
| { | |
| "key": "s114", | |
| "label": "π¨ Council S114 / Bankruptcy Notice", | |
| "urgency": "critical", | |
| "query": ( | |
| 'UK council "section 114" OR "s114 notice" OR "issued section 114" ' | |
| 'OR "declared effective bankruptcy" OR "financial emergency" ' | |
| f'site:gov.uk OR site:lgcplus.com OR site:localgov.co.uk ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "lgr_decision", | |
| "label": "ποΈ Government LGR Unitary Decision", | |
| "urgency": "critical", | |
| "query": ( | |
| '"local government reorganisation" ("government confirms" OR "minister announces" ' | |
| 'OR "approved" OR "unitary authority confirmed" OR "structural changes confirmed") ' | |
| f'site:gov.uk OR site:lgcplus.com OR site:bbc.co.uk ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "lgr_appointment", | |
| "label": "π€ Senior LGR Appointment", | |
| "urgency": "high", | |
| "query": ( | |
| 'site:linkedin.com ("delighted to join" OR "pleased to announce" OR "excited to share") ' | |
| '("programme director" OR "director of transformation" OR "lgr") ' | |
| '("county council" OR "unitary authority") ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "competitor_win", | |
| "label": "π― Competitor Win at LGR Council", | |
| "urgency": "high", | |
| "query": ( | |
| '("county council" OR "local authority") ' | |
| '("working with" OR "appointed" OR "partnering with" OR "contract awarded to") ' | |
| '("McKinsey" OR "Deloitte" OR "KPMG" OR "PwC" OR "PA Consulting" OR "Optio" ' | |
| '"Moorhouse" OR "Arcadis" OR "Mott MacDonald") ' | |
| '("transformation" OR "LGR" OR "reorganisation") ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "herts_decision", | |
| "label": "ποΈ Hertfordshire LGR β Any Development", | |
| "urgency": "high", | |
| "query": ( | |
| '"Hertfordshire" ("unitary" OR "LGR" OR "reorganisation" OR "programme director") ' | |
| '("announces" OR "confirms" OR "appointed" OR "decision") ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "essex_lgr", | |
| "label": "ποΈ Essex LGR β Any Development", | |
| "urgency": "high", | |
| "query": ( | |
| '"Essex County Council" ("unitary" OR "LGR" OR "reorganisation" OR "programme director" ' | |
| 'OR "transformation") ("announces" OR "confirms" OR "appointed" OR "decision") ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "lancashire_lgr", | |
| "label": "ποΈ Lancashire LGR β Any Development", | |
| "urgency": "high", | |
| "query": ( | |
| '"Lancashire County Council" ("unitary" OR "LGR" OR "reorganisation" OR "programme director") ' | |
| '("announces" OR "confirms" OR "appointed" OR "decision") ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "priority_counties_lgr", | |
| "label": "ποΈ Priority LGR Counties β Surrey/Hampshire/Kent/Norfolk/Suffolk", | |
| "urgency": "high", | |
| "query": ( | |
| '("Surrey County Council" OR "Hampshire County Council" OR "Kent County Council" ' | |
| 'OR "Norfolk County Council" OR "Suffolk County Council" OR "Warwickshire County Council" ' | |
| 'OR "Gloucestershire County Council" OR "Oxfordshire County Council") ' | |
| '("LGR" OR "unitary" OR "reorganisation" OR "programme director" OR "transformation lead") ' | |
| '("appointed" OR "confirms" OR "decision" OR "announces" OR "contract") ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| { | |
| "key": "lgr_govt_consultation_outcome", | |
| "label": "ποΈ MHCLG β Any LGR Consultation Outcome", | |
| "urgency": "critical", | |
| "query": ( | |
| 'site:gov.uk "local government reorganisation" ' | |
| '("consultation outcome" OR "government response" OR "decision letter" ' | |
| 'OR "unitary authority order" OR "structural changes order") ' | |
| f'after:{date.today().isoformat()}' | |
| ), | |
| }, | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Seen-events dedup β stored as a JSON file alongside leads.db | |
| # --------------------------------------------------------------------------- | |
| _SEEN_PATH = REPO_ROOT / "data" / "realtime_alert_seen.json" | |
| def _load_seen() -> set[str]: | |
| try: | |
| return set(json.loads(_SEEN_PATH.read_text())) | |
| except Exception: | |
| return set() | |
| def _save_seen(seen: set[str]) -> None: | |
| _SEEN_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| _SEEN_PATH.write_text(json.dumps(sorted(seen))) | |
| def _event_key(watch_key: str, text: str) -> str: | |
| """Stable hash for a (watch_key, result_text) pair.""" | |
| return hashlib.sha1(f"{watch_key}:{text[:200]}".encode()).hexdigest()[:16] | |
| # --------------------------------------------------------------------------- | |
| # Search + parse | |
| # --------------------------------------------------------------------------- | |
| def _run_watch(client: Anthropic, watch: dict) -> list[dict]: | |
| """Run one watchlist query. Returns list of hit dicts.""" | |
| try: | |
| resp = client.messages.create( | |
| model="claude-haiku-4-5", | |
| max_tokens=800, | |
| tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 1}], | |
| messages=[{ | |
| "role": "user", | |
| "content": ( | |
| f"Search for: {watch['query']}\n\n" | |
| f"Return ONLY a JSON array of hits (empty array [] if nothing found today).\n" | |
| f"Each hit: {{\"title\": \"...\", \"url\": \"...\", \"snippet\": \"...\"}}\n" | |
| f"Maximum 3 hits. Only include items published TODAY or in the last 24 hours.\n" | |
| f"If nothing is genuinely new, return []." | |
| ), | |
| }], | |
| ) | |
| text = "".join(b.text for b in resp.content if hasattr(b, "text")).strip() | |
| # Extract JSON array | |
| import re | |
| m = re.search(r"\[.*\]", text, re.S) | |
| if not m: | |
| return [] | |
| return json.loads(m.group(0)) or [] | |
| except Exception as e: | |
| print(f" Watch {watch['key']} error: {e}") | |
| return [] | |
| # --------------------------------------------------------------------------- | |
| # Alert email | |
| # --------------------------------------------------------------------------- | |
| def _build_alert_html(hits_by_watch: list[tuple[dict, list[dict]]]) -> str: | |
| parts = [ | |
| '<div style="font-family:Calibri,Arial,sans-serif;max-width:640px;margin:0 auto;">', | |
| '<h2 style="color:#b71c1c;border-bottom:2px solid #b71c1c;padding-bottom:6px;">' | |
| 'π¨ Curium β Real-Time Intelligence Alert</h2>', | |
| f'<p style="color:#546e7a;font-size:0.85em;">' | |
| f'Generated: {datetime.utcnow().strftime("%Y-%m-%d %H:%M")} UTC</p>', | |
| ] | |
| for watch, hits in hits_by_watch: | |
| urgency_colour = "#b71c1c" if watch["urgency"] == "critical" else "#e65100" | |
| parts.append( | |
| f'<h3 style="color:{urgency_colour};margin-top:20px;">' | |
| f'{watch["label"]}</h3>' | |
| ) | |
| for h in hits: | |
| title = h.get("title", "No title") | |
| url = h.get("url", "") | |
| snippet = h.get("snippet", "") | |
| parts.append( | |
| f'<div style="border-left:3px solid {urgency_colour};' | |
| f'padding:8px 12px;margin:8px 0;background:#fafafa;">' | |
| f'<div style="font-weight:600;">' | |
| + (f'<a href="{url}" style="color:#1565c0;">{title}</a>' if url else title) | |
| + f'</div>' | |
| f'<div style="font-size:0.88em;color:#555;margin-top:4px;">{snippet}</div>' | |
| f'</div>' | |
| ) | |
| # Shared platform feedback footer β every platform email carries it. | |
| # Alerts go to several people, so pass no recipient name (the web form | |
| # works for anyone). Falls back gracefully if the module isn't importable. | |
| fb = "" | |
| try: | |
| import sys as _sys | |
| _sys.path.insert(0, str(REPO_ROOT)) | |
| import weekly_digest as _wd | |
| fb = _wd._feedback_prompt_html(recipient_name=None) | |
| except Exception: | |
| fb = "" | |
| parts.append(fb) | |
| parts.append( | |
| '<p style="font-size:0.8em;color:#9e9e9e;margin-top:24px;border-top:1px solid #eee;' | |
| 'padding-top:8px;">Curium Lead Intelligence β real-time tier-1 alert</p>' | |
| '</div>' | |
| ) | |
| return "".join(parts) | |
| # --------------------------------------------------------------------------- | |
| # Main | |
| # --------------------------------------------------------------------------- | |
| def main() -> int: | |
| api_key = os.environ.get("ANTHROPIC_API_KEY", "").strip() | |
| if not api_key: | |
| print("ANTHROPIC_API_KEY not set β exiting") | |
| return 1 | |
| admin_email = os.environ.get("ADMIN_EMAIL", "").strip() | |
| if not admin_email: | |
| print("ADMIN_EMAIL not set β nowhere to send alerts") | |
| return 1 | |
| client = Anthropic(api_key=api_key) | |
| seen = _load_seen() | |
| new_hits: list[tuple[dict, list[dict]]] = [] | |
| for watch in WATCHLIST: | |
| print(f"β Checking: {watch['label']}β¦") | |
| hits = _run_watch(client, watch) | |
| fresh = [] | |
| for h in hits: | |
| key = _event_key(watch["key"], h.get("title", "") + h.get("url", "")) | |
| if key not in seen: | |
| fresh.append(h) | |
| seen.add(key) | |
| if fresh: | |
| print(f" π΄ {len(fresh)} new hit(s)") | |
| new_hits.append((watch, fresh)) | |
| else: | |
| print(f" β Nothing new") | |
| time.sleep(1) | |
| if not new_hits: | |
| print("No new tier-1 signals β nothing to send") | |
| _save_seen(seen) | |
| return 0 | |
| # Build and send alert | |
| html = _build_alert_html(new_hits) | |
| critical = any(w["urgency"] == "critical" for w, _ in new_hits) | |
| subject = ( | |
| f"π¨ URGENT β Curium tier-1 alert: {new_hits[0][0]['label']}" | |
| if critical else | |
| f"β‘ Curium intelligence alert: {len(new_hits)} new signal(s)" | |
| ) | |
| # Alert recipients β explicit list, never auto-broadcast to whole team. | |
| # Add/remove names here to control who gets real-time alerts. | |
| ALERT_RECIPIENT_NAMES = {"Piers", "Stu", "Henriette", "Jordan"} | |
| import yaml | |
| try: | |
| with open(REPO_ROOT / "config.yaml") as f: | |
| cfg = yaml.safe_load(f) or {} | |
| alert_emails: list[str] = [] | |
| for entry in (cfg.get("team_emails") or []): | |
| name = entry.get("name", "") | |
| email = entry.get("email", "") | |
| if name not in ALERT_RECIPIENT_NAMES: | |
| continue | |
| if not email or email.startswith("ENV:"): | |
| # Resolve ENV: references | |
| if email.startswith("ENV:"): | |
| email = os.environ.get(email[4:], "").strip() | |
| if not email: | |
| continue | |
| alert_emails.append(email) | |
| except Exception as e: | |
| print(f" (config read failed, falling back to ADMIN_EMAIL: {e})") | |
| alert_emails = [admin_email] | |
| # Deduplicate | |
| alert_emails = list(dict.fromkeys(e for e in alert_emails if e)) | |
| if not alert_emails: | |
| alert_emails = [admin_email] | |
| for email in alert_emails: | |
| result = mailer.send(to_email=email, subject=subject, html=html) | |
| if result.get("success"): | |
| print(f"β Alert sent to {email}") | |
| else: | |
| print(f"β Send failed for {email}: {result.get('message')}") | |
| _save_seen(seen) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |