---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Rescore all 0-scored cope_entries and pipeline_results using MiniMax.\"\"\" import sys, os, json, re, time, sqlite3, requests from datetime import datetime, timezone sys.path.insert(0."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-04-29T18:09:24Z"
site: "uk"
source_path: "copecheck-uk/rescore_zeros.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/rescore_zeros.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-04-29T18:09:24Z`

```py
#!/usr/bin/env python3
"""Rescore all 0-scored cope_entries and pipeline_results using MiniMax."""
import sys, os, json, re, time, sqlite3, requests
from datetime import datetime, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from dotenv import load_dotenv
load_dotenv()

[redacted secret-like line]
MINIMAX_URL = 'https://api.minimax.io/v1/chat/completions'
DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'copecheck_uk.db')

COPE_SCORING_PROMPT = """You are the UK CopeCheck Oracle. Score how much "cope" (denial, deflection, false reassurance, minimisation) is present in this quote/claim.

Figure: {name} ({role})
Quote/Claim: {quote}

If the quote contains NO relevant economic/AI/structural claim (e.g. it's about football, personal matters, or no claim is attributed), score it LOW (0-15) and set cope_type to "irrelevant".

If the quote DOES contain cope about AI, jobs, economy, or structural issues, score 0-100:
- 0-20: Lucid (honest acknowledgment)
- 21-40: Partial cope
- 41-60: Moderate cope
- 61-80: Heavy cope
- 81-100: Terminal copium

Respond EXACTLY in this format:
COPE_SCORE: [number]
COPE_TYPE: [type]
ANALYSIS: [1-2 sentences]"""

def call_minimax(prompt):
    resp = requests.post(
        MINIMAX_URL,
[redacted secret-like line]
        json={
            'model': 'minimax-m2.7',
            'messages': [
                {'role': 'system', 'content': 'You are a sardonic British political analyst. Be brief and precise.'},
                {'role': 'user', 'content': prompt}
            ],
            'temperature': 0.3,
[redacted secret-like line]
        },
        timeout=30
    )
    resp.raise_for_status()
    data = resp.json()
    content = data['choices'][0]['message']['content']
    content = re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL).strip()
    return content

def parse_score(raw):
    m = re.search(r'COPE_SCORE:\s*(\d+)', raw)
    score = float(m.group(1)) if m else 0.0
    m2 = re.search(r'COPE_TYPE:\s*(.+?)(?:\n|$)', raw)
    cope_type = m2.group(1).strip() if m2 else 'unknown'
    m3 = re.search(r'ANALYSIS:\s*(.+)', raw, re.DOTALL)
    analysis = m3.group(1).strip()[:500] if m3 else ''
    return score, cope_type, analysis

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

    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row

    # Get figure info for lookups
    figures = {}
    for f in conn.execute("SELECT id, name, role FROM figures").fetchall():
        figures[f['id']] = dict(f)

    # 1. Rescore cope_entries with 0 scores
    zeros = conn.execute(
        "SELECT id, figure_id, quote, cope_type FROM cope_entries WHERE cope_score = 0"
    ).fetchall()
    print(f"Rescoring {len(zeros)} cope_entries...")

    success = 0
    for i, row in enumerate(zeros):
        fig = figures.get(row['figure_id'], {'name': 'Unknown', 'role': 'Unknown'})
        quote = row['quote'] or ''
        if len(quote) < 10:
            print(f"  [{i+1}/{len(zeros)}] id={row['id']} - skipping (no quote)")
            continue

        try:
            prompt = COPE_SCORING_PROMPT.format(
                name=fig['name'], role=fig.get('role', ''), quote=quote[:500]
            )
            raw = call_minimax(prompt)
            score, cope_type, analysis = parse_score(raw)

            conn.execute(
                "UPDATE cope_entries SET cope_score = ?, cope_type = ?, analysis_md = ?, model = ? WHERE id = ?",
                (score, cope_type, analysis, 'minimax/minimax-m2.7', row['id'])
            )
            conn.commit()
            print(f"  [{i+1}/{len(zeros)}] id={row['id']} {fig['name']}: {score} ({cope_type})")
            success += 1
            time.sleep(0.5)
        except Exception as e:
            print(f"  [{i+1}/{len(zeros)}] id={row['id']} FAILED: {e}")

    print(f"\ncope_entries: {success}/{len(zeros)} rescored")

    # 2. Rescore pipeline_results with 0 scores that have actual claims
    p_zeros = conn.execute(
        "SELECT id, figure_id, claim_summary, source_url FROM pipeline_results WHERE cope_score = 0 AND source_url IS NOT NULL AND source_url != ''"
    ).fetchall()
    print(f"\nRescoring {len(p_zeros)} pipeline_results...")

    p_success = 0
    for i, row in enumerate(p_zeros):
        fig = figures.get(row['figure_id'], {'name': 'Unknown', 'role': 'Unknown'})
        claim = row['claim_summary'] or ''
        if len(claim) < 10:
            print(f"  [{i+1}/{len(p_zeros)}] id={row['id']} - skipping (no claim)")
            continue

        try:
            prompt = COPE_SCORING_PROMPT.format(
                name=fig['name'], role=fig.get('role', ''), quote=claim[:500]
            )
            raw = call_minimax(prompt)
            score, cope_type, analysis = parse_score(raw)

            # Determine band
            if score <= 20: band = 'lucid'
            elif score <= 40: band = 'partial'
            elif score <= 60: band = 'moderate'
            elif score <= 80: band = 'heavy_cope'
            else: band = 'terminal'

            conn.execute(
                "UPDATE pipeline_results SET cope_score = ?, band = ?, primary_mode = ?, rationale_short = ?, model = ? WHERE id = ?",
                (score, band, cope_type, analysis, 'minimax/minimax-m2.7', row['id'])
            )
            conn.commit()
            print(f"  [{i+1}/{len(p_zeros)}] id={row['id']} {fig['name']}: {score} ({cope_type})")
            p_success += 1
            time.sleep(0.5)
        except Exception as e:
            print(f"  [{i+1}/{len(p_zeros)}] id={row['id']} FAILED: {e}")

    print(f"\npipeline_results: {p_success}/{len(p_zeros)} rescored")
    print(f"\nTotal: {success + p_success} rescored")
    conn.close()

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