---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" Round 2: Targeted Brave Search scorer for Rain Newton-Smith and Tim Martin. Passes FULL article text to pipeline instead of just context window, and uses better search queries targeting."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-04-25T05:58:58Z"
site: "uk"
source_path: "copecheck-uk/brave_scorer_v2.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/brave_scorer_v2.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-04-25T05:58:58Z`

```py
#!/usr/bin/env python3
"""
Round 2: Targeted Brave Search scorer for Rain Newton-Smith and Tim Martin.
Passes FULL article text to pipeline instead of just context window,
and uses better search queries targeting statements/opinions.
"""
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_v2")

[redacted secret-like line]
MIN_BODY = 300
MAX_PER_FIGURE = 3

# Better queries targeting actual statements/opinions
TARGET_FIGURES = {
    "newton_smith": [
        '"Rain Newton-Smith" said economy',
        '"Rain Newton-Smith" CBI business confidence',
        '"Newton-Smith" CBI investment UK growth',
        'CBI chief executive economy investment skills',
    ],
    "martin": [
        '"Tim Martin" said Wetherspoon tax',
        '"Tim Martin" Wetherspoons Brexit wages staff',
        '"Tim Martin" hospitality economy pubs',
        'Wetherspoon chairman economy immigration staff shortages',
    ],
}

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 get_figure_data(fig_id):
    for f in SEED_FIGURES:
        if f["id"] == fig_id:
            return f
    return None


def brave_search(query, count=10):
    """Search using Brave Search API."""
[redacted secret-like line]
[redacted secret-like line]
    url = "https://api.search.brave.com/res/v1/web/search"
[redacted secret-like line]
    # Use pw (past week) for freshness to get more results, or remove for all time
    params = {"q": query, "count": count, "country": "gb", "search_lang": "en"}
    try:
        resp = requests.get(url, headers=headers, params=params, timeout=15)
        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."""
    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):
    pat = re.compile(r'\b' + re.escape(name.lower()) + r'\b')
    return bool(pat.search(text.lower()))


def should_skip_url(url):
    for d in SKIP_DOMAINS:
        if d in url.lower():
            return True
    return False


def score_and_save(fig, full_text, source_url, source_title, source_name):
    """Run scoring pipeline with FULL article text (not just context window)."""
    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:
        # Pass full text as pre_fetched_text - the pipeline will extract claims itself
        result = scoring_pipeline.score_article(
            url=source_url, person=person, source_name=source_name,
            pre_fetched_text=full_text, pre_fetched_title=source_title,
        )
        scoring_pipeline.save_raw_log(result, fig["id"])
        if result.get("published") and result.get("score"):
            score_val = result["score"].get("cope_score", 0)
            # Skip score=0 articles (not real cope content)
            if score_val == 0:
                log.info("  score=0 (no cope content), skipping save")
                return None
            scoring_pipeline.save_pipeline_result(result, fig["id"], db)
            band = result["score"].get("band")
            stage = result.get("stage")
            log.info("  SCORED %s: score=%s band=%s stage=%s url=%s", fig["name"], score_val, 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


def main():
    log.info("=== CopeCheck UK Brave Scorer v2 (Newton-Smith + Martin) ===")
    db.init()
    seen_urls = set()
    total_scored = 0

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

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

        for query in queries:
            if scored_this_fig >= MAX_PER_FIGURE:
                break

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

            for r in results:
                if scored_this_fig >= MAX_PER_FIGURE:
                    break

                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):
                    # Also try last name only for Newton-Smith
                    last = fig["name"].split()[-1]
                    if not name_in_text(last, combined):
                        log.info("    GATE: '%s' not in article text", fig["name"])
                        continue

                log.info("    name found (%d chars), scoring with full text...", len(body))
                result = score_and_save(fig, body, url, fetched_title, "brave_search")
                if result:
                    scored_this_fig += 1
                    total_scored += 1

                time.sleep(1.5)
            time.sleep(1)

        log.info("  %s: %d new scores", fig["name"], scored_this_fig)

    log.info("=== DONE === Total new scored: %d", total_scored)

    # 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[:5]:
            log.info("  score=%s type=%s url=%s", e.get("cope_score"), e.get("cope_type"), str(e.get("source_url",""))[:70])


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