---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Rescore 6 YouTube videos with updated context: Andy Burnham is now UK PM.\"\"\" import sys, os, json, re, sqlite3, requests from datetime import datetime sys.path.insert(0."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-12T12:14:05Z"
site: "uk"
source_path: "copecheck-uk/rescore_burnham_pm.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/rescore_burnham_pm.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-12T12:14:05Z`

```py
#!/usr/bin/env python3
"""Rescore 6 YouTube videos with updated context: Andy Burnham is now UK PM."""

import sys, os, json, re, sqlite3, requests
from datetime import datetime

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

from youtube_scorer import (
    get_transcript,
    COPE_SYSTEM_PROMPT,
[redacted secret-like line]
    MINIMAX_URL,
    MINIMAX_MODEL,
    MAX_TRANSCRIPT_CHARS,
    apply_omission_cope_correction,
)

DB_PATH = "/home/ben/infra/copecheck-uk/data/copecheck_uk.db"
[redacted secret-like line]
SEP = "=" * 60

BURNHAM_PM_CONTEXT = """POLITICAL CONTEXT UPDATE (mandatory -- bake into your scoring):
Andy Burnham was Mayor of Greater Manchester when this video was recorded. He is now UK Prime Minister.

Score this video with that updated political reality fully baked in:
- Any "Manchesterism," devolution, or regional regeneration vision he presents must now be evaluated knowing he holds the highest office and will implement (or fail to implement) these promises at national scale.
- Any failure to mention AI-driven structural displacement is even more consequential cope now that he is PM -- silence on structural AI economics from a sitting Prime Minister is categorically more dangerous cope than silence from a regional mayor.
- Commentators who speculated about whether Burnham could "save Labour" or become PM should be scored on whether that speculative framing assumed the problem was political strategy rather than the structural economic crisis AI is creating -- if they were cheerleading for Burnham as the political answer while never naming the actual structural problem, score accordingly.
- If the video positioned Burnham as a hopeful political alternative to Starmer, evaluate whether that hope was grounded in any confrontation with structural AI economics, or pure political optimism cope.

"""


def score_with_context(transcript, title, channel):
    if len(transcript) > MAX_TRANSCRIPT_CHARS:
        transcript = transcript[:MAX_TRANSCRIPT_CHARS]

    user_prompt = BURNHAM_PM_CONTEXT + 'VIDEO: "' + title + '" by ' + channel + "\n\nTRANSCRIPT:\n" + transcript

    full_prompt = (COPE_SYSTEM_PROMPT + "\n\n---\n\nUSER REQUEST:\n"
                   + user_prompt + "\n\nReturn ONLY valid JSON.")

    # Primary: Codex
    try:
        resp = requests.post(N8N_URL, json={"prompt": full_prompt}, timeout=360)
        if resp.status_code == 200:
            data = resp.json()
            if data.get("cope_score") is not None:
                print("  Codex score=" + str(data["cope_score"]))
                return {
                    "cope_score": data["cope_score"],
                    "summary": data.get("summary", ""),
                    "scapegoats": data.get("scapegoats", ""),
                    "cope_mechanisms": data.get("cope_mechanisms", ""),
                    "key_quotes": data.get("key_quotes", []),
                    "scorer": "codex",
                }
        print("  Codex HTTP " + str(resp.status_code) + ": " + resp.text[:200])
    except Exception as e:
        print("  Codex error: " + str(e))

    # Fallback: MiniMax
    print("  Falling back to MiniMax...")
[redacted secret-like line]
[redacted secret-like line]
        return None
    try:
[redacted secret-like line]
        payload = {
            "model": MINIMAX_MODEL,
            "messages": [
                {"role": "system", "content": COPE_SYSTEM_PROMPT},
                {"role": "user", "content": user_prompt[:100000]},
            ],
[redacted secret-like line]
            "temperature": 0.7,
        }
        resp = requests.post(MINIMAX_URL, headers=headers, json=payload, timeout=120)
        if resp.status_code == 200:
            text = resp.json()["choices"][0]["message"]["content"]
            text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
            text = re.sub(r"^```(?:json)?\n?", "", text)
            text = re.sub(r"\n?```$", "", text)
            result = json.loads(text)
            result["scorer"] = "minimax"
            print("  MiniMax score=" + str(result.get("cope_score")))
            return result
        print("  MiniMax HTTP " + str(resp.status_code) + ": " + resp.text[:150])
    except Exception as e:
        print("  MiniMax error: " + str(e))

    return None


def main():
    conn = sqlite3.connect(DB_PATH)
    rows = conn.execute(
        "SELECT id, video_id, title, channel, cope_score FROM youtube_videos WHERE id IN (44,48,49,67,81,82) ORDER BY id"
    ).fetchall()

    print("Rescoring " + str(len(rows)) + " videos with Burnham-PM context\n")
    summary = []

    for db_id, video_id, title, channel, old_score in rows:
        print("\n" + SEP)
        print("DB id=" + str(db_id) + " | video_id=" + video_id)
        print("Title: " + title)
        print("Old score: " + str(old_score))

        print("  Fetching transcript...")
        transcript = get_transcript(video_id)
        if not transcript:
            print("  FAILED: no transcript")
            summary.append((db_id, title, old_score, None, "TRANSCRIPT_FAILED"))
            continue
        print("  Transcript: " + str(len(transcript)) + " chars")

        scored = score_with_context(transcript, title, channel)
        if not scored:
            print("  FAILED: scoring returned None")
            summary.append((db_id, title, old_score, None, "SCORING_FAILED"))
            continue

        new_score = float(scored["cope_score"])
        key_quotes = scored.get("key_quotes", [])
        if isinstance(key_quotes, list):
            key_quotes_str = json.dumps(key_quotes)
        else:
            key_quotes_str = str(key_quotes)

        conn.execute(
            "UPDATE youtube_videos SET cope_score=?, cope_summary=?, scapegoats=?, cope_mechanisms=?, key_quotes=?, scored_at=?, status='scored' WHERE id=?",
            (new_score, scored.get("summary", ""), scored.get("scapegoats", ""),
             scored.get("cope_mechanisms", ""), key_quotes_str,
             datetime.utcnow().isoformat(), db_id)
        )
        conn.commit()
        delta = new_score - old_score
        print("  NEW SCORE: " + str(new_score) + " (delta " + ("+%.1f" % delta if delta >= 0 else "%.1f" % delta) + ")")
        summary.append((db_id, title, old_score, new_score, scored.get("scorer", "?")))

    print("\n\n" + SEP)
    print("RESCORE SUMMARY (Burnham now UK PM context)")
    print(SEP)
    for db_id, title, old, new, scorer in summary:
        if new is None:
            print("  ID " + str(db_id) + ": FAILED (" + str(scorer) + ") | " + title[:55])
        else:
            delta = new - old
            sign = "+" if delta >= 0 else ""
            print("  ID " + str(db_id) + ": " + str(int(old)) + " -> " + str(int(new)) + " (" + sign + "%.1f" % delta + ") [" + scorer + "] | " + title[:55])

    conn.close()


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