---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Rescore the complete active UK Cope index with the current Oracle model. Unlike the legacy utility, this updates the cope_entries records that actually drive the public leaderboard. Historical."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-04T21:44:56Z"
site: "uk"
source_path: "copecheck-uk/rescore_figures_oracle.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/rescore_figures_oracle.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-04T21:44:56Z`

```py
#!/usr/bin/env python3
"""Rescore the complete active UK Cope index with the current Oracle model.

Unlike the legacy utility, this updates the cope_entries records that actually
drive the public leaderboard. Historical timestamps and source links are kept.
"""
import argparse
import concurrent.futures
import json
import sqlite3
import sys
from datetime import datetime, timezone
from pathlib import Path

sys.path.insert(0, "/home/ben/infra/copecheck-uk")

from dotenv import load_dotenv

load_dotenv("/home/ben/infra/copecheck-uk/.env")

import db_uk as db
import oracle_uk as oracle

DB_PATH = "/home/ben/infra/copecheck-uk/data/copecheck_uk.db"
LOG_DIR = Path("/home/ben/infra/copecheck-uk/logs")


def _normalise_type(value):
    """Collapse free-form model labels to the site's public taxonomy."""
    text = (value or "").strip().lower()
    if "scapegoat" in text:
        return "scapegoating"
    if "gaslight" in text:
        return "gaslighting"
    if "fantasy" in text or "utopian" in text or "solutionist" in text:
        return "fantasy_economics"
    if "denial" in text or "denialist" in text:
        return "denial"
    if "minimis" in text or "partial" in text:
        return "minimisation"
    if "lucid" in text or "structural" in text:
        return "lucid"
    if "deflect" in text or "cope" in text or "technocratic" in text:
        return "deflection"
    return "unknown"


def _score(item):
    context = f"Source: {item['source_title'] or 'Unknown source'}"
    result = oracle.score_figure_cope(
        item["name"], item["role"] or "", item["quote"], context
    )
    return item, result


def _sync_figure(conn, figure_id):
    row = conn.execute(
        "SELECT cope_score, role, type, category FROM figures WHERE id = ?",
        (figure_id,),
    ).fetchone()
    if not row:
        return
    entries = db._public_entries(conn, figure_id)
    if not entries:
        conn.execute(
            """UPDATE figures SET cope_score=0, total_quotes=0,
               last_scored=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
               WHERE id=?""",
            (figure_id,),
        )
        return
    score = db._public_cope_index(entries, row["role"], row["type"], row["category"])
    latest = entries[0]
    conn.execute(
        """UPDATE figures SET cope_score=?, prev_score=?, total_quotes=?,
           latest_incident=?, last_quote=?, last_cope_type=?,
           last_scored=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
           WHERE id=?""",
        (
            score,
            row["cope_score"],
            len(entries),
            db._format_latest_incident(latest),
            (latest.get("quote") or "")[:500],
            latest.get("cope_type") or "",
            figure_id,
        ),
    )


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--limit", type=int, default=0)
    parser.add_argument("--resume-after-id", type=int, default=0)
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.row_factory = sqlite3.Row
    rows = conn.execute(
        """SELECT e.id AS entry_id, e.figure_id, e.quote, e.source_title,
                  e.cope_score AS old_score, e.cope_type AS old_type,
                  e.model AS old_model, f.name, f.role
           FROM cope_entries e
           JOIN figures f ON f.id=e.figure_id
           WHERE COALESCE(f.active,1)=1
             AND e.id > ?
             AND lower(COALESCE(e.cope_type,'')) NOT IN
                 ('unknown','n/a','none','other','irrelevant','')
           ORDER BY e.id""",
        (args.resume_after_id,),
    ).fetchall()
    items = [dict(row) for row in rows]
    if args.limit:
        items = items[: args.limit]

    print(f"Rescoring {len(items)} public entries across the active UK index")
    if args.dry_run:
        counts = {}
        for item in items:
            counts[item["name"]] = counts.get(item["name"], 0) + 1
        print(json.dumps(counts, indent=2, sort_keys=True))
        return 0

    started = datetime.now(timezone.utc).isoformat()
    audit = {
        "started_at": started,
        "completed_at": None,
        "requested": len(items),
        "succeeded": 0,
        "failed": 0,
        "last_entry_id": args.resume_after_id,
        "results": [],
    }
    touched = set()

    with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.workers)) as pool:
        futures = {pool.submit(_score, item): item for item in items}
        for n, future in enumerate(concurrent.futures.as_completed(futures), 1):
            item = futures[future]
            record = {
                "entry_id": item["entry_id"],
                "figure_id": item["figure_id"],
                "name": item["name"],
                "old_score": item["old_score"],
                "old_model": item["old_model"],
            }
            try:
                _, result = future.result()
                if not result or result.get("cope_score") is None:
                    raise RuntimeError("Oracle returned no score")
                new_score = float(result["cope_score"])
                new_type = _normalise_type(result.get("cope_type"))
                new_model = result.get("model") or "unknown"
                analysis = (result.get("analysis") or "").strip()
                conn.execute(
                    """UPDATE cope_entries
                       SET cope_score=?, cope_type=?, analysis_md=?, model=?
                       WHERE id=?""",
                    (new_score, new_type, analysis, new_model, item["entry_id"]),
                )
                conn.commit()
                touched.add(item["figure_id"])
                audit["succeeded"] += 1
                record.update(
                    status="ok", new_score=new_score, cope_type=new_type, model=new_model
                )
            except Exception as exc:
                audit["failed"] += 1
                record.update(status="failed", error=str(exc)[:300])
            audit["last_entry_id"] = max(audit["last_entry_id"], item["entry_id"])
            audit["results"].append(record)
            print(
                f"[{n}/{len(items)}] {item['name']} entry={item['entry_id']} "
                f"status={record['status']} score={record.get('new_score', '-')}"
            )

    for figure_id in sorted(touched):
        _sync_figure(conn, figure_id)
    conn.commit()
    conn.close()

    audit["completed_at"] = datetime.now(timezone.utc).isoformat()
    LOG_DIR.mkdir(exist_ok=True)
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    audit_path = LOG_DIR / f"full-index-rescore-{stamp}.json"
    audit_path.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8")
    print(f"Audit: {audit_path}")
    print(f"Succeeded: {audit['succeeded']} Failed: {audit['failed']}")
    return 1 if audit["failed"] else 0


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