---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" Brave Search scorer for CopeCheck main site figures. Uses Brave Search API -> trafilatura -> oracle.score_cope() pipeline. \"\"\" import hashlib import logging import os import re import sys."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-26T09:57:59Z"
site: "main"
source_path: "copecheck/brave_scorer.py"
---

# !/usr/bin/env python3

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

```py
#!/usr/bin/env python3
"""
Brave Search scorer for CopeCheck main site figures.
Uses Brave Search API -> trafilatura -> oracle.score_cope() pipeline.
"""
import hashlib
import logging
import os
import re
import sys
import time
from pathlib import Path

import requests
import trafilatura
import yaml

sys.path.insert(0, os.path.dirname(__file__))
import db
import oracle
from canonical_identity import canonical_url, canonical_url_hash, same_event
from content_quality import extraction_quality_issue

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s | %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler(
            str(Path(__file__).parent / "logs" / "brave_scorer.log"),
            encoding="utf-8",
        ),
    ],
)
log = logging.getLogger("brave_scorer")

[redacted secret-like line]

HOME_SCRAPER_URL = os.environ.get("FIRECRAWL_URL", "http://100.70.233.73:3002").rstrip("/")
FIGURES_PATH = Path(__file__).parent / "figures.yaml"
MIN_BODY = 300
FETCH_TIMEOUT = 25
# Per-run insert limit: keep only the top and bottom N by cope_score
KEEP_TOP = 3
KEEP_BOTTOM = 3
AUTO_PUBLISH_ATTRIBUTION = {
    "direct_quote", "named_paraphrase", "contextual_attribution",
    "institutional_report",
}
MIN_CONFIDENCE = 0.6

# Skip domains 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 load_figures():
    """Load figures from figures.yaml."""
    if not FIGURES_PATH.exists():
        log.warning("figures.yaml not found at %s", FIGURES_PATH)
        return []
    with open(FIGURES_PATH) as f:
        data = yaml.safe_load(f)
    return data.get("figures", [])


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"
    headers = {
        "Accept": "application/json",
        "Accept-Encoding": "gzip",
[redacted secret-like line]
    }
    params = {"q": query, "count": count, "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 from the Home VPS first, then fall back to trafilatura."""
    try:
        response = requests.post(
            f"{HOME_SCRAPER_URL}/v1/scrape",
            json={"url": url, "formats": ["markdown"]},
            timeout=30,
        )
        response.raise_for_status()
        data = response.json()
        if data.get("success"):
            scraped = data.get("data", {})
            text = (scraped.get("markdown") or "").strip()
            title = scraped.get("metadata", {}).get("title", "")
            if text:
                return text, title
    except Exception as e:
        log.debug("Home scraper failed for %s: %s", url[:60], e)

    try:
        downloaded = trafilatura.fetch_url(url)
        if not downloaded:
            return "", ""
        text = trafilatura.extract(downloaded, include_comments=False) or ""
        metadata = trafilatura.extract(downloaded, output_format="json", include_comments=False)
        title = ""
        if metadata:
            import json
            try:
                meta = json.loads(metadata)
                title = meta.get("title", "")
            except Exception:
                pass
        return text, title
    except Exception as e:
        log.debug("trafilatura failed for %s: %s", url[:60], e)
        return "", ""


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 extract_figure_context(text, name, window=800):
    """Extract text around mentions of a figure. Requires strong name match."""
    lower = text.lower()
    name_lower = name.lower()
    last_name = name.split()[-1].lower()

    def _word_boundary_find(haystack, needle):
        positions = []
        pattern = re.compile(r'\b' + re.escape(needle) + r'\b')
        for m in pattern.finditer(haystack):
            positions.append(m.start())
        return positions

    full_positions = _word_boundary_find(lower, name_lower)
    last_positions = []
    if len(last_name) >= 4:
        last_positions = _word_boundary_find(lower, last_name)

    if full_positions:
        positions = sorted(set(full_positions + last_positions))
    elif len(last_positions) >= 2:
        positions = last_positions
    else:
        return ""

    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 main():
    log.info("=== CopeCheck Brave Search Scorer ===")
    db.init()

[redacted secret-like line]
[redacted secret-like line]
        sys.exit(1)

    figures = load_figures()
    if not figures:
        log.error("No figures loaded from figures.yaml")
        sys.exit(1)

    log.info("Loaded %d figures", len(figures))
    seen_urls = set()

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

    for fig in figures:
        queries = fig.get("search_queries", [])
        if not queries:
            continue

        fig_id = fig["id"]
        fig_name = fig["name"]
        fig_title = fig.get("title", "")
        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"]

                run_key = (fig_id, canonical_url_hash(url))
                if run_key in seen_urls or should_skip_url(url):
                    continue
                seen_urls.add(run_key)

                # Check if already scored for this figure
                if db.record_cope_observation_if_known(
                    fig_id, "", source_url=url, source_title=title,
                    channel="brave",
                ):
                    log.info("  already scored for figure: %s", url[:60])
                    continue

                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
                issue = extraction_quality_issue(body)
                if issue:
                    log.info("    extraction rejected (%s)", issue)
                    continue

                quote_context = extract_figure_context(body, fig_name)
                if not quote_context or len(quote_context) < 80:
                    log.info("    no/short context for %s", fig_name)
                    continue

                if db.record_cope_observation_if_known(
                    fig_id, quote_context, source_url=url,
                    source_title=fetched_title, channel="brave",
                ):
                    log.info("    cope entry already exists")
                    continue

                try:
                    log.info("    name found, scoring via oracle...")
                    cope_result = oracle.score_cope(
                        fig_name, fig_title,
                        quote_context,
                        source_context=f"From: {fetched_title}",
                    )
                    # Skip irrelevant zero-score entries
                    if cope_result["cope_score"] == 0 and cope_result.get("cope_type") == "N/A":
                        log.info("    SKIPPED %s: score=0 type=N/A (irrelevant)", fig_name)
                        continue
                    ctype = cope_result.get("cope_type", "").lower().strip()
                    if cope_result.get("cope_score", 0) < 0 or "not_attributed" in ctype or ctype == "n/a":
                        continue
                    if cope_result.get("attribution_strength", "mentioned_only") not in AUTO_PUBLISH_ATTRIBUTION:
                        continue
                    if float(cope_result.get("confidence", 0.0) or 0.0) < MIN_CONFIDENCE:
                        continue
                    if cope_result.get("needs_review"):
                        continue

                    # Cluster inside the run before top/bottom selection so a
                    # syndicated story cannot crowd out independent evidence.
                    candidate = {
                        "cope_score": cope_result["cope_score"],
                        "figure_id": fig_id,
                        "figure_name": fig_name,
                        "article_slug": None,
                        "quote": cope_result.get("cope_quote") or quote_context[:300],
                        "source_url": url,
                        "source_title": fetched_title,
                        "cope_type": cope_result.get("cope_type", "unknown"),
                        "analysis_md": cope_result.get("analysis", ""),
                        "model": cope_result.get("model", ""),
                        "provenance": [],
                    }
                    merged = False
                    for existing in all_scored:
                        if existing["figure_id"] != fig_id:
                            continue
                        if same_event(
                            canonical_a=canonical_url(candidate["source_url"]),
                            title_a=candidate["source_title"],
                            quote_a=candidate["quote"],
                            canonical_b=canonical_url(existing["source_url"]),
                            title_b=existing["source_title"],
                            quote_b=existing["quote"],
                        ):
                            existing["provenance"].append(candidate)
                            merged = True
                            break
                    if not merged:
                        all_scored.append(candidate)
                    scored_this_fig += 1
                    log.info("    CANDIDATE %s: score=%s type=%s",
                             fig_name, cope_result.get("cope_score"),
                             cope_result.get("cope_type"))
                except Exception as e:
                    log.warning("    scoring error for %s: %s", fig_name, e)

                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["source_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:
        for observation in [entry] + entry.get("provenance", []):
            result = db.add_cope_entry(
                figure_id=observation["figure_id"],
                article_slug=observation["article_slug"],
                quote=observation["quote"],
                source_url=observation["source_url"],
                source_title=observation["source_title"],
                cope_score=observation["cope_score"],
                cope_type=observation["cope_type"],
                analysis_md=observation["analysis_md"],
                model=observation["model"],
                channel="brave",
            )
            if result and result.get("inserted"):
                total_inserted += 1
        log.info(
            "  INSERTED %s (score=%s type=%s)",
            entry["source_url"][:60], entry["cope_score"], entry["cope_type"],
        )

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


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)
```
