---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" Direct news scanner for CopeCheck UK — bypasses Google News redirect issues by using direct RSS feeds and resolving Google News URLs before fetching. \"\"\" import json import logging import os."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-12T15:46:09Z"
site: "uk"
source_path: "copecheck-uk/cope_runner.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/cope_runner.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-12T15:46:09Z`

```py
#!/usr/bin/env python3
"""
Direct news scanner for CopeCheck UK — bypasses Google News redirect issues
by using direct RSS feeds and resolving Google News URLs before fetching.
"""
import json
import logging
import os
import re
import sys
import time
from datetime import datetime, timezone
from urllib.parse import quote_plus

import feedparser
import requests
import trafilatura

sys.path.insert(0, os.path.dirname(__file__))
import db_uk as db
import scoring_pipeline
from seed_data import FIGURES as SEED_FIGURES

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s | %(message)s",
    handlers=[logging.StreamHandler()],
)
log = logging.getLogger("cope_runner")

FIRECRAWL_URL = os.environ.get("FIRECRAWL_URL", "http://100.70.233.73:3002").rstrip("/")
MIN_BODY = 300
MAX_PER_FIGURE = 3


def resolve_google_news_url(url, timeout=10):
    """Resolve a Google News redirect URL to the actual article URL."""
    if "news.google.com" not in url:
        return url
    try:
        resp = requests.get(url, allow_redirects=True, timeout=timeout,
                           headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})
        final = resp.url
        if "consent.google.com" in final or "news.google.com" in final:
            # Try extracting from the page content
            match = re.search(r'href="(https?://(?!news\.google\.com)[^"]+)"', resp.text)
            if match:
                return match.group(1)
            # Try the data-url attribute
            match2 = re.search(r'data-url="(https?://[^"]+)"', resp.text)
            if match2:
                return match2.group(1)
            return None
        return final
    except Exception as e:
        log.warning("resolve failed for %s: %s", url[:80], e)
        return None


def fetch_article(url):
    """Fetch article text, trying Firecrawl first, then trafilatura."""
    try:
        result = scoring_pipeline.fetch_article_firecrawl(url)
        md = result.get("markdown", "")
        if md:
            return scoring_pipeline._strip_boilerplate(md)
    except Exception as e:
        log.debug("Firecrawl failed for %s: %s", url[:60], e)
    try:
        downloaded = trafilatura.fetch_url(url)
        if downloaded:
            text = trafilatura.extract(downloaded, include_comments=False,
                                       include_tables=False, favor_recall=True)
            return (text or "").strip()
    except Exception:
        pass
    return ""


def extract_context(text, name, window=800):
    """Extract text around mentions of a figure."""
    lower = text.lower()
    name_lower = name.lower()
    pat = re.compile(r'\b' + re.escape(name_lower) + r'\b')
    positions = [m.start() for m in pat.finditer(lower)]
    if not positions:
        return ""
    # Also include last-name matches
    last = name.split()[-1].lower()
    if len(last) >= 4:
        lp = re.compile(r'\b' + re.escape(last) + r'\b')
        positions = sorted(set(positions + [m.start() for m in lp.finditer(lower)]))
    chunks = []
    for pos in positions[:3]:
        s = max(0, pos - window // 2)
        e = min(len(text), pos + window // 2)
        chunks.append(text[s:e])
    return "\n...\n".join(chunks)


def name_in_text(name, text):
    """Word-boundary check: full name must appear in text."""
    pat = re.compile(r'\b' + re.escape(name.lower()) + r'\b')
    return bool(pat.search(text.lower()))


# --- Direct RSS feeds that give actual URLs (not Google News redirects) ---
DIRECT_FEEDS = [
    ("BBC Politics", "https://feeds.bbci.co.uk/news/politics/rss.xml"),
    ("BBC Business", "https://feeds.bbci.co.uk/news/business/rss.xml"),
    ("Guardian Politics", "https://www.theguardian.com/politics/rss"),
    ("Guardian Economics", "https://www.theguardian.com/business/economics/rss"),
    ("Sky News Politics", "https://feeds.skynews.com/feeds/rss/politics.xml"),
    ("Independent Politics", "https://www.independent.co.uk/news/uk/politics/rss"),
]

# Per-figure direct search URLs (no Google News)
def gnews_search(query, max_results=5):
    """Use GNews API if key available, else return empty."""
[redacted secret-like line]
    if not key:
        return []
    try:
        resp = requests.get("https://gnews.io/api/v4/search", params={
            "q": query, "lang": "en", "country": "gb",
[redacted secret-like line]
        }, timeout=15)
        resp.raise_for_status()
        return resp.json().get("articles", [])
    except Exception as e:
        log.warning("GNews API error: %s", e)
        return []


def google_news_rss(query):
    """Fetch Google News RSS and resolve URLs."""
    url = (f"https://news.google.com/rss/search?"
           f"q={quote_plus(query + ' when:7d')}&hl=en-GB&gl=GB&ceid=GB:en")
    try:
        parsed = feedparser.parse(url)
        results = []
        for entry in parsed.entries[:8]:
            raw_url = entry.get("link", "")
            title = (entry.get("title") or "").strip()
            if not raw_url or not title:
                continue
            resolved = resolve_google_news_url(raw_url)
            if resolved:
                results.append({"url": resolved, "title": title})
        return results
    except Exception as e:
        log.warning("Google News RSS error: %s", e)
        return []


def score_and_save(fig, quote_context, source_url, source_title, source_name):
    """Run the scoring pipeline and save result."""
    person = {
        "id": fig["id"],
        "name": fig["name"],
        "role": fig.get("role", ""),
        "party": fig.get("party", ""),
    }
    if db.pipeline_url_scored(source_url, fig["id"]):
        log.info("  already scored: %s", source_url[:60])
        return None
    try:
        result = scoring_pipeline.score_article(
            url=source_url,
            person=person,
            source_name=source_name,
            pre_fetched_text=quote_context,
            pre_fetched_title=source_title,
        )
        scoring_pipeline.save_raw_log(result, fig["id"])
        if result.get("published") and result.get("score"):
            scoring_pipeline.save_pipeline_result(result, fig["id"], db)
            score = result["score"].get("cope_score")
            band = result["score"].get("band")
            stage = result.get("stage")
            log.info("  SCORED %s: score=%s band=%s stage=%s", fig["name"], score, band, stage)
            return result
        elif result.get("reject_reason"):
            log.info("  rejected: %s", result["reject_reason"])
        else:
            log.info("  no result returned")
    except Exception as e:
        log.warning("  scoring error: %s", e)
    return None


def main():
    log.info("=== CopeCheck UK Direct Runner ===")
    figures = SEED_FIGURES
    results = {f["name"]: [] for f in figures}
    seen_urls = set()

    # PHASE 1: Scan direct RSS feeds and match against all figures
    log.info("--- Phase 1: Direct RSS feeds ---")
    for feed_name, feed_url in DIRECT_FEEDS:
        try:
            parsed = feedparser.parse(feed_url)
        except Exception:
            continue
        for entry in parsed.entries[:15]:
            url = entry.get("link", "")
            title = (entry.get("title") or "").strip()
            if not url or not title or url in seen_urls:
                continue
            seen_urls.add(url)

            # Quick title check - does any figure name appear?
            title_lower = title.lower()
            matching_figs = [f for f in figures if f["name"].split()[-1].lower() in title_lower]
            if not matching_figs:
                continue

            log.info("Title match in '%s': %s", feed_name, title[:80])
            body = fetch_article(url)
            if len(body) < MIN_BODY:
                log.info("  body too short (%d chars), skipping", len(body))
                continue

            combined = title + " " + body
            for fig in matching_figs:
                if len(results[fig["name"]]) >= MAX_PER_FIGURE:
                    continue
                if not name_in_text(fig["name"], combined):
                    log.info("  GATE: '%s' not in article text, skipping", fig["name"])
                    continue
                ctx = extract_context(body, fig["name"])
                if not ctx or len(ctx) < 80:
                    continue
                if db.cope_entry_exists(fig["id"], ctx[:200]):
                    log.info("  duplicate entry for %s, skipping", fig["name"])
                    continue
                log.info("  queuing %s for scoring", fig["name"])
                r = score_and_save(fig, ctx, url, title, feed_name)
                if r:
                    results[fig["name"]].append({"title": title, "url": url, "score": r.get("score", {})})
            time.sleep(0.5)

    # PHASE 2: Per-figure Google News search with URL resolution
    log.info("--- Phase 2: Per-figure Google News search ---")
    for fig in figures:
        if len(results[fig["name"]]) >= MAX_PER_FIGURE:
            log.info("Skipping %s, already has %d results", fig["name"], len(results[fig["name"]]))
            continue

        queries = fig.get("search_queries", [fig["name"] + " UK economy"])
        scored = 0

        for query in queries[:2]:  # limit queries
            if scored >= MAX_PER_FIGURE:
                break
            log.info("Google News search: '%s'", query)
            articles = google_news_rss(query)
            for art in articles:
                if scored >= MAX_PER_FIGURE:
                    break
                url = art["url"]
                title = art["title"]
                if url in seen_urls:
                    continue
                seen_urls.add(url)

                body = fetch_article(url)
                if len(body) < MIN_BODY:
                    continue
                combined = title + " " + body
                if not name_in_text(fig["name"], combined):
                    log.info("  GATE: '%s' not found in article", fig["name"])
                    continue
                ctx = extract_context(body, fig["name"])
                if not ctx or len(ctx) < 80:
                    continue
                if db.cope_entry_exists(fig["id"], ctx[:200]):
                    log.info("  duplicate for %s", fig["name"])
                    continue
                log.info("  queuing %s from '%s'", fig["name"], title[:60])
                r = score_and_save(fig, ctx, url, title, "google_news")
                if r:
                    results[fig["name"]].append({"title": title, "url": url, "score": r.get("score", {})})
                    scored += 1
                time.sleep(1)
        time.sleep(0.5)


    # Summary
    log.info("=== RESULTS ===")
    total_new = 0
    for name, entries in sorted(results.items()):
        if entries:
            total_new += len(entries)
            for e in entries:
                sc = e.get("score", {})
                log.info("  %s: score=%s band=%s | %s",
                         name, sc.get("cope_score"), sc.get("band"), e["title"][:70])
        else:
            log.info("  %s: no new articles matched", name)

    log.info("Total new scored entries: %d", total_new)

    # Final DB counts
    counts = db.counts()
    log.info("Final DB counts: %s", counts)
    log.info("=== Done ===")


if __name__ == "__main__":
    main()
```
