---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" Targeted Brave Search scorer for CopeCheck UK figures with no real scored articles. Uses Brave Search API -> Firecrawl -> tiered scoring pipeline. \"\"\" import json, logging, os, re, sys, time."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-09-26T09:57:59Z"
site: "uk"
source_path: "copecheck-uk/brave_scorer.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/brave_scorer.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-26T09:57:59Z`

```py
#!/usr/bin/env python3
"""
Targeted Brave Search scorer for CopeCheck UK figures with no real scored articles.
Uses Brave Search API -> Firecrawl -> tiered scoring pipeline.
"""
import json, logging, os, re, sys, time
from urllib.parse import quote_plus

import requests

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")
log = logging.getLogger("brave_scorer")

[redacted secret-like line]
FIRECRAWL_URL = os.environ.get("FIRECRAWL_URL", "http://100.70.233.73:3002").rstrip("/")
MIN_BODY = 300
# Per-run insert limit: keep only the top and bottom N by cope_score
KEEP_TOP = 3
KEEP_BOTTOM = 3

# Target figures and their search queries
TARGET_FIGURES = {
    "dyson": [
        "James Dyson UK economy jobs manufacturing",
        "James Dyson Brexit business regulation",
        "James Dyson innovation skills Britain",
    ],
    "ratcliffe": [
        "Jim Ratcliffe INEOS Manchester United economy",
        "Jim Ratcliffe investment UK business",
        "Jim Ratcliffe energy costs competitiveness",
    ],
    "newton_smith": [
        "Rain Newton-Smith CBI economy business investment",
        "Rain Newton-Smith skills planning reform",
        "CBI Rain Newton-Smith competitiveness",
    ],
    "martin": [
        "Tim Martin Wetherspoons economy Brexit",
        "Tim Martin immigration wages hospitality",
        "Tim Martin tax burden pubs",
    ],

    "rian_sheridan": [
        "Rian Sheridan UK economy regulation",
        "Rian Sheridan housing wages immigration",
        "Rian Sheridan economic decline policy failure",
    ],
}

def get_figure_data(fig_id):
    for f in SEED_FIGURES:
        if f["id"] == fig_id:
            return f
    return None


class BraveQuotaExhausted(RuntimeError):
    """The monthly Brave Search plan quota is spent."""


# Brave returns HTTP 429 both for the per-second rate limit and for a spent
# monthly quota. They are completely different conditions: the first is
# transient and the next run succeeds, the second means every remaining call
# this month will fail, so a run that keeps going "successfully" inserts nothing
# while reporting success. error.code and the monthly component of
# x-ratelimit-remaining tell them apart.
_QUOTA_STATE = {"exhausted": False, "detail": ""}


def _quota_exhaustion_detail(resp):
    """Return a detail string if this 429 is monthly-quota exhaustion, else None."""
    try:
        body = resp.json()
    except Exception:  # noqa: BLE001 - a non-JSON 429 is simply not classifiable
        body = {}
    error = (body.get("error") or {}) if isinstance(body, dict) else {}
    meta = error.get("meta") or {}
    code = str(error.get("code") or "")
    remaining = [p.strip() for p in resp.headers.get("x-ratelimit-remaining", "").split(",")]
    monthly_spent = len(remaining) > 1 and remaining[1] == "0"
    if code != "QUOTA_LIMITED" and not monthly_spent:
        return None
    detail = "plan=%s quota=%s/%s code=%s" % (
        meta.get("plan", "?"),
        meta.get("quota_current", "?"),
        meta.get("quota_limit", "?"),
        code or "429",
    )
    reset = [p.strip() for p in resp.headers.get("x-ratelimit-reset", "").split(",")]
    if len(reset) > 1 and reset[1].isdigit():
        detail += " resets_in_days=%.1f" % (int(reset[1]) / 86400.0)
    return detail


def brave_search(query, count=8):
    """Search using Brave Search API. Returns list of {url, title, description}."""
    # Once the monthly quota is gone every further call is a guaranteed 429, so
    # stop spending wall-clock time and log lines on them.
    if _QUOTA_STATE["exhausted"]:
        return []
[redacted secret-like line]
[redacted secret-like line]
    url = "https://api.search.brave.com/res/v1/web/search"
[redacted secret-like line]
    params = {"q": query, "count": count, "country": "gb", "search_lang": "en", "freshness": "pm"}
    try:
        resp = requests.get(url, headers=headers, params=params, timeout=15)
        if resp.status_code == 429:
            detail = _quota_exhaustion_detail(resp)
            if detail:
                _QUOTA_STATE["exhausted"] = True
                _QUOTA_STATE["detail"] = detail
                log.error(
                    "Brave monthly quota EXHAUSTED (%s) - abandoning all remaining "
                    "searches this run. No candidates can be found until the quota "
                    "resets; this run will exit non-zero.", detail,
                )
                return []
        resp.raise_for_status()
        data = resp.json()
        results = []
        for r in data.get("web", {}).get("results", []):
            results.append({
                "url": r.get("url", ""),
                "title": r.get("title", ""),
                "description": r.get("description", ""),
            })
        return results
    except Exception as e:
        log.warning("Brave search error for '%s': %s", query, e)
        return []


def fetch_article(url):
    """Fetch article text via Firecrawl, return cleaned text."""
    try:
        result = scoring_pipeline.fetch_article_firecrawl(url)
        md = result.get("markdown", "")
        if md:
            return scoring_pipeline._strip_boilerplate(md), result.get("title", "")
    except Exception as e:
        log.debug("Firecrawl failed for %s: %s", url[:60], e)
    return "", ""


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


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)]
    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)]))
    if not positions:
        return ""
    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 score_only(fig, quote_context, source_url, source_title, source_name):
    """Run the scoring pipeline without saving to DB.
    Saves the raw audit log as usual. Returns result dict if accepted, else None."""
    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"):
            score = result["score"].get("cope_score")
            band = result["score"].get("band")
            stage = result.get("stage")
            log.info("  CANDIDATE %s: score=%s band=%s stage=%s url=%s",
                     fig["name"], score, band, stage, source_url[:60])
            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 for %s: %s", fig["name"], e)
    return None


# Skip domains that are unlikely to have scorable content
SKIP_DOMAINS = {
    "wikipedia.org", "britannica.com", "linkedin.com", "twitter.com",
    "x.com", "facebook.com", "instagram.com", "youtube.com",
    "imdb.com", "amazon.com", "reddit.com", "tiktok.com",
}

def should_skip_url(url):
    """Skip reference/social URLs that won't have scorable articles."""
    for d in SKIP_DOMAINS:
        if d in url.lower():
            return True
    return False


def main():
    log.info("=== CopeCheck UK Brave Search Scorer ===")
    db.init()
    seen_urls = set()

    # Collect all scored candidates this run; only insert top+bottom N at the end
    all_scored = []

    for fig_id, queries in TARGET_FIGURES.items():
        fig = get_figure_data(fig_id)
        if not fig:
            log.warning("Figure %s not found in seed data", fig_id)
            continue

        log.info("--- Processing: %s (%s) ---", fig["name"], fig_id)
        scored_this_fig = 0

        for query in queries:
            log.info("Brave search: '%s'", query)
            results = brave_search(query)
            log.info("  got %d results", len(results))

            for r in results:
                url = r["url"]
                title = r["title"]

                if url in seen_urls or should_skip_url(url):
                    continue
                seen_urls.add(url)

                log.info("  trying: %s", url[:80])
                body, fetched_title = fetch_article(url)
                if not fetched_title:
                    fetched_title = title

                if len(body) < MIN_BODY:
                    log.info("    body too short (%d chars)", len(body))
                    continue

                combined = (fetched_title or "") + " " + body
                if not name_in_text(fig["name"], combined):
                    log.info("    GATE: '%s' not in article text", fig["name"])
                    continue

                ctx = extract_context(body, fig["name"])
                if not ctx or len(ctx) < 80:
                    log.info("    context too short")
                    continue

                log.info("    name found, scoring...")
                result = score_only(fig, ctx, url, fetched_title, "brave_search")
                if result:
                    cope_score = result["score"].get("cope_score")
                    if cope_score is None:
                        # Unscoreable: scorer returned an explicit null. Skip rather
                        # than coercing to 0 (matches main-site behaviour) — a None
                        # here previously crashed the top/bottom sort below.
                        log.info("    unscoreable (cope_score is None) - skipping")
                    else:
                        all_scored.append({
                            "cope_score": cope_score,
                            "fig_id": fig_id,
                            "fig": fig,
                            "result": result,
                        })
                        scored_this_fig += 1

                time.sleep(1.5)  # Rate limit between articles

            time.sleep(1)  # Rate limit between queries

        log.info("  %s: %d candidates scored this run", fig["name"], scored_this_fig)

    log.info("Total candidates scored this run: %d", len(all_scored))

    # ── Filter: keep only top KEEP_TOP + bottom KEEP_BOTTOM by cope_score ──
    if len(all_scored) <= KEEP_TOP + KEEP_BOTTOM:
        to_insert = all_scored
    else:
        sorted_desc = sorted(all_scored, key=lambda x: x["cope_score"], reverse=True)
        top = sorted_desc[:KEEP_TOP]
        bottom = sorted_desc[-KEEP_BOTTOM:]
        # Deduplicate (overlap possible when very few candidates)
        seen_keys: set = set()
        to_insert = []
        for entry in top + bottom:
            key = entry["result"].get("url", "")
            if key not in seen_keys:
                seen_keys.add(key)
                to_insert.append(entry)

    log.info(
        "Keeping %d articles (top %d + bottom %d) out of %d candidates",
        len(to_insert), KEEP_TOP, KEEP_BOTTOM, len(all_scored),
    )

    total_inserted = 0
    for entry in to_insert:
        scoring_pipeline.save_pipeline_result(entry["result"], entry["fig_id"], db)
        total_inserted += 1
        score = entry["cope_score"]
        url_short = str(entry["result"].get("url", ""))[:60]
        log.info("  INSERTED score=%s url=%s", score, url_short)

    log.info("=== DONE === Inserted %d / %d candidates", total_inserted, len(all_scored))
    counts = db.counts()
    log.info("DB counts: %s", counts)

    # Show results for target figures
    for fig_id in TARGET_FIGURES:
        entries = db.figure_entries(fig_id)
        real = [e for e in entries if e.get("cope_score", 0) > 0]
        log.info("%s: %d total entries, %d with real scores", fig_id, len(entries), len(real))
        for e in real[:3]:
            log.info("  score=%s type=%s url=%s", e.get("cope_score"), e.get("cope_type"), str(e.get("source_url",""))[:60])


if __name__ == "__main__":
    main()
    if _QUOTA_STATE["exhausted"]:
        # Exit non-zero so an exhausted quota stops masquerading as a clean run.
        log.error(
            "=== BRAVE QUOTA EXHAUSTED === %s. Searches were skipped, so any insert "
            "count above reflects only work already in hand, not new discovery. "
            "Exiting 2.",
            _QUOTA_STATE["detail"],
        )
        sys.exit(2)
```
