---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" Rescore v2: Re-scan all analyzed articles against tracked figures. Handles MiniMax rate limiting with retries and backoff. Run via: /home/ben/infra/copecheck/run_rescore.sh (uses this."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-05-11T09:11:24Z"
site: "main"
source_path: "copecheck/rescore_v2.py"
---

# !/usr/bin/env python3

Source path: `copecheck/rescore_v2.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-05-11T09:11:24Z`

```py
#!/usr/bin/env python3
"""
Rescore v2: Re-scan all analyzed articles against tracked figures.
Handles MiniMax rate limiting with retries and backoff.
Run via: /home/ben/infra/copecheck/run_rescore.sh (uses this instead)
"""
import logging
import time
import sys
import os

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

# Patch oracle.score_cope to add retry logic with backoff
import oracle
_orig_score_cope = oracle.score_cope

def _score_cope_with_retry(figure_name, figure_title, quote, source_context="",
                           max_retries=2, base_delay=5):
    """Wrapper around score_cope with retry + backoff for API failures."""
    for attempt in range(max_retries + 1):
        try:
            result = _orig_score_cope(figure_name, figure_title, quote, source_context)
            return result
        except Exception as e:
            if attempt < max_retries:
                delay = base_delay * (2 ** attempt)
                log.warning("score_cope attempt %d failed for %s, retrying in %ds: %s",
                           attempt + 1, figure_name, delay, str(e)[:100])
                time.sleep(delay)
            else:
                raise

oracle.score_cope = _score_cope_with_retry

import db
import pipeline

db.init()
pipeline.sync_figures()

# Get all analyzed articles with body text
with db.conn() as c:
    cur = c.execute(
        "SELECT * FROM articles WHERE status = 'analysed' AND body IS NOT NULL "
        "ORDER BY id ASC"
    )
    articles = [dict(r) for r in cur.fetchall()]

log.info("Rescoring %d analyzed articles against all tracked figures...", len(articles))

total_scored = 0
total_skipped = 0
total_errors = 0
api_calls = 0

for i, article in enumerate(articles):
    if i % 100 == 0 and i > 0:
        with db.conn() as c:
            n = c.execute("SELECT COUNT(*) FROM cope_entries").fetchone()[0]
        log.info("=== Progress: %d/%d articles | %d entries | %d api calls | %d errors ===",
                 i, len(articles), n, api_calls, total_errors)

    try:
        oracle_result = {"verdict_md": article.get("verdict_md", "")}
        pipeline._crosslink_figures(article, oracle_result)
    except Exception as e:
        total_errors += 1
        log.warning("Error on article %s: %s", article.get("slug", "?")[:40], str(e)[:100])
        # Don't abort on errors — just keep going
        time.sleep(3)  # Extra delay after errors

# Final stats
with db.conn() as c:
    final = c.execute("SELECT COUNT(*) FROM cope_entries").fetchone()[0]
    fig_count = c.execute("SELECT COUNT(DISTINCT figure_id) FROM cope_entries").fetchone()[0]
    top = c.execute(
        "SELECT f.name, f.cope_score, f.total_quotes FROM figures f "
        "WHERE f.total_quotes > 0 ORDER BY f.total_quotes DESC"
    ).fetchall()

log.info("=== RESCORE COMPLETE ===")
log.info("Total cope entries: %d", final)
log.info("Figures with entries: %d", fig_count)
log.info("Total errors: %d", total_errors)
for fig in top:
    log.info("  %s: score=%.1f, quotes=%d", fig[0], fig[1], fig[2])
```
