---
type: "Source File"
title: "\"\"\"YouTube Cope Scorer - pulls transcripts and scores them via MiniMax.\"\"\""
description: "\"\"\"YouTube Cope Scorer - pulls transcripts and scores them via MiniMax.\"\"\" import os from datetime import datetime, timezone import io import re import json import time import logging import sqlite3 import traceback."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-10-24T12:42:28Z"
site: "uk"
source_path: "copecheck-uk/youtube_scorer.py"
---

# """YouTube Cope Scorer - pulls transcripts and scores them via MiniMax."""

Source path: `copecheck-uk/youtube_scorer.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-10-24T12:42:28Z`

```py
"""YouTube Cope Scorer - pulls transcripts and scores them via MiniMax."""
import os
from datetime import datetime, timezone
import io
import re
import json
import time
import logging
import sqlite3
import traceback
import requests
from datetime import datetime
from youtube_transcript_api import YouTubeTranscriptApi

[redacted secret-like line]
MINIMAX_URL = "https://api.minimax.io/v1/chat/completions"
MINIMAX_MODEL = "MiniMax-M3"

# n8n Codex primary scorer
[redacted secret-like line]

[redacted secret-like line]
MAX_TRANSCRIPT_CHARS = 60000
# Browser Act API config
[redacted secret-like line]
BROWSERACT_TEMPLATE_ID = "87197468034420377"  # YouTube Transcript Extractor API
BROWSERACT_BASE_URL = "https://api.browseract.com/v2/workflow"

# ── Logging & attempt tracking ─────────────────────────────────────────────
_LOG_PATH = os.path.join(os.path.dirname(__file__), "logs", "youtube_scoring.log")
os.makedirs(os.path.dirname(_LOG_PATH), exist_ok=True)
_yt_logger = logging.getLogger("youtube_scorer")
if not _yt_logger.handlers:
    _yt_logger.setLevel(logging.INFO)
    _fh = logging.FileHandler(_LOG_PATH)
    _fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
    _yt_logger.addHandler(_fh)
    _sh = logging.StreamHandler()
    _sh.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
    _yt_logger.addHandler(_sh)

_YOUTUBE_DB = os.path.join(os.path.dirname(__file__), "data", "copecheck_uk.db")

def robust_json_parse(text):
    """Parse JSON from oracle response with field-by-field fallback for malformed output.
    
    Long-form fields (video_summary, dt_verdict, butchers_verdict) can contain
    unescaped newlines/quotes that break json.loads. This function tries clean parse
    first, then falls back to per-field regex extraction.
    """
    # Strip <think> tags (MiniMax sometimes includes them)
    text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
    # Strip markdown code fences
    if text.startswith('```'):
        text = re.sub(r'^```(?:json)?\n?', '', text)
        text = re.sub(r'\n?```$', '', text)

    # Find JSON block
    json_match = re.search(r'\{.*\}', text, re.DOTALL)
    if not json_match:
        return None
    json_str = json_match.group(0)

    # Try clean parse first
    try:
        return json.loads(json_str)
    except json.JSONDecodeError:
        pass

    # Fallback: extract fields individually via regex
    result = {}

    # Numeric field
    m = re.search(r'"cope_score"\s*:\s*([\d.]+)', json_str)
    if m:
        result['cope_score'] = float(m.group(1))

    # Long text fields - match quoted strings handling escaped chars
    for field in ['summary', 'video_summary', 'dt_verdict', 'butchers_verdict']:
        m = re.search(rf'"{field}"\s*:\s*"((?:[^"\\]|\\.)*)"'  , json_str, re.DOTALL)
        if m:
            val = m.group(1)
            val = val.replace('\\n', '\n').replace('\\\"'  , '"').replace('\\\\'  , '\\')
            result[field] = val

    # Short text fields
    for field in ['scapegoats', 'cope_mechanisms']:
        m = re.search(rf'"{field}"\s*:\s*"((?:[^"\\]|\\.)*)"'  , json_str, re.DOTALL)
        if m:
            result[field] = m.group(1)

    # Array field
    m = re.search(r'"key_quotes"\s*:\s*\[(.*?)\]', json_str, re.DOTALL)
    if m:
        items = re.findall(r'"((?:[^"\\]|\\.)*)"'  , m.group(1))
        result['key_quotes'] = [i.replace('\\n', '\n').replace('\\\"'  , '"') for i in items]

    return result if result.get('cope_score') is not None else None




def _persist_raw_scoring_failure(raw_text, source, video_title=None, detail=None):
    """Write an unparseable scoring response to disk, in full.

    Both callers previously logged `str(...)[:200]` and nothing else. The
    2026-10-20 failure on Rqt9kWoTJbc broke at character 957 - four times past
    that cut - so the log recorded that a parse failed but not a single
    character of the text that caused it, and the only full copy died with the
    process. These files are what make the next occurrence readable.
    """
    try:
        import pathlib
        target_dir = pathlib.Path(__file__).parent / "logs" / "raw_scoring_failures"
        target_dir.mkdir(parents=True, exist_ok=True)
        stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
        path = target_dir / ("scorer-%s-%s.txt" % (source, stamp))
        body = (
            "# source: %s\n# captured_at_utc: %s\n# title: %s\n"
            "# detail: %s\n# raw_length: %s\n%s\n"
            % (source, stamp, (video_title or "")[:200], (detail or ""),
               len(raw_text or ""), "-" * 60)
        )
        with io.open(path, "w", encoding="utf-8", errors="replace") as handle:
            handle.write(body)
            handle.write(raw_text or "")
        try:
            os.chmod(path, 0o600)
        except Exception:
            pass
        _yt_logger.warning(
            "Persisted unparseable %s scoring response (%d chars) to %s",
            source, len(raw_text or ""), path.name,
        )
        return str(path)
    except Exception as exc:
        _yt_logger.warning("Could not persist raw scoring response: %s", exc)
        return None


def _ensure_attempts_table():
    """Create youtube_score_attempts log table if it does not exist."""
    conn = sqlite3.connect(_YOUTUBE_DB)
    conn.execute("""CREATE TABLE IF NOT EXISTS youtube_score_attempts (
        id         INTEGER PRIMARY KEY AUTOINCREMENT,
        video_id   TEXT,
        title      TEXT,
        attempt_num INTEGER DEFAULT 1,
        status     TEXT,
        error_msg  TEXT,
        scored_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )""")
    conn.commit()
    conn.close()


def _log_attempt(video_id, title, attempt_num, status, error_msg=None):
    """Log a scoring attempt to DB + log file."""
    _yt_logger.info(
        "ATTEMPT video_id=%s title=%r attempt=%d status=%s error=%s",
        video_id, (title or "")[:80], attempt_num, status, error_msg or ""
    )
    try:
        _ensure_attempts_table()
        conn = sqlite3.connect(_YOUTUBE_DB)
        conn.execute(
            "INSERT INTO youtube_score_attempts "
            "(video_id, title, attempt_num, status, error_msg) "
            "VALUES (?, ?, ?, ?, ?)",
            (video_id or "", title or "", attempt_num, status, error_msg or "")
        )
        conn.commit()
        conn.close()
    except Exception as _exc:
        _yt_logger.warning("_log_attempt: DB write failed: %s", _exc)



def extract_video_id(url):
    """Extract YouTube video ID from various URL formats."""
    patterns = [
        r"(?:v=|/v/|youtu\.be/)([a-zA-Z0-9_-]{11})",
        r"(?:embed/)([a-zA-Z0-9_-]{11})",
        r"youtube\.com/live/([a-zA-Z0-9_-]{11})",
        r"youtube\.com/shorts/([a-zA-Z0-9_-]{11})",
        r"^([a-zA-Z0-9_-]{11})$",
    ]
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    return None


def get_transcript_via_browseract(video_id):
    """PRIMARY: Fetch transcript via Browser Act YouTube Transcript Extractor API.

    Uses the official template to navigate YouTube, extract transcript text,
    and return it. Handles async polling with timeout.
    """
[redacted secret-like line]
        print("Browser Act: no API key configured")
        return None

    headers = {
[redacted secret-like line]
        "Content-Type": "application/json",
    }
    video_url = f"https://www.youtube.com/watch?v={video_id}"

    # Step 1: Create task from template
    try:
        resp = requests.post(
            f"{BROWSERACT_BASE_URL}/run-task-by-template",
            headers=headers,
            json={
                "workflow_template_id": BROWSERACT_TEMPLATE_ID,
                "input_parameters": [
                    {"name": "TargetURL", "value": video_url}
                ],
            },
            timeout=30,
        )
        if resp.status_code != 200:
            print(f"Browser Act: task creation failed ({resp.status_code}): {resp.text[:200]}")
            return None

        task_id = resp.json().get("id")
        if not task_id:
            print("Browser Act: no task_id in response")
            return None
        print(f"Browser Act: task created {task_id}")
    except Exception as e:
        print(f"Browser Act: task creation error: {e}")
        return None

    # Step 2: Poll for completion (max ~6 minutes, check every 10 seconds)
    max_polls = 30  # ~300 seconds sleep + HTTP overhead
    for i in range(max_polls):
        time.sleep(10)
        try:
            status_resp = requests.get(
                f"{BROWSERACT_BASE_URL}/get-task-status",
[redacted secret-like line]
                params={"task_id": task_id},
                timeout=15,
            )
            if status_resp.status_code != 200:
                print(f"Browser Act: status check failed ({status_resp.status_code})")
                continue

            status = status_resp.json().get("status", "unknown")
            if status == "finished":
                break
            elif status in ("failed", "canceled"):
                print(f"Browser Act: task {status}")
                return None
            # else: created, running, pausing, paused — keep polling
        except Exception as e:
            print(f"Browser Act: status poll error: {e}")
            continue
    else:
        print("Browser Act: task timed out after ~6 minutes")
        return None

    # Step 3: Get task output
    try:
        result_resp = requests.get(
            f"{BROWSERACT_BASE_URL}/get-task",
[redacted secret-like line]
            params={"task_id": task_id},
            timeout=30,
        )
        if result_resp.status_code != 200:
            print(f"Browser Act: get-task failed ({result_resp.status_code})")
            return None

        task_data = result_resp.json()
        output_str = (task_data.get("output") or {}).get("string") or ""
        if not output_str:
            # The template finished but emitted nothing. Nearly always the last
            # step could not find YouTube's "Show transcript" control, so log
            # the step trail rather than the opaque "no output string".
            steps = task_data.get("steps") or []
            print("Browser Act: task finished with no output "
                  f"({len(steps)} step(s), {task_data.get('credit')} credits)")
            for s in steps:
                print(f"  Browser Act step {s.get('step')}: {s.get('status')} "
                      f"| {(s.get('step_goal') or '')[:120]}")
            failure = task_data.get("task_failure_info")
            if failure:
                print(f"  Browser Act failure info: {str(failure)[:200]}")
            print("  Browser Act: if the last step is a FALSE 'Show transcript' "
                  "check, the workflow template needs updating in the Browser "
                  "Act console - this is not a client-side bug.")
            return None

        # Parse the output — it's a JSON array of items
        items = json.loads(output_str)
        if isinstance(items, list) and len(items) > 0:
            transcript = items[0].get("transcript", "")
        elif isinstance(items, dict):
            transcript = items.get("transcript", "")
        else:
            transcript = ""

        if transcript:
            # Clean up music note characters that Browser Act sometimes adds
            transcript = transcript.replace("♪", "").strip()
            # Collapse excess whitespace
            transcript = re.sub(r'\s+', ' ', transcript).strip()
            print(f"Browser Act: transcript extracted, {len(transcript)} chars")
            return transcript
        else:
            print("Browser Act: no transcript in output")
            return None
    except Exception as e:
        print(f"Browser Act: output parsing error: {e}")
        return None


def get_transcript(video_id):
    """Fetch transcript -- fast methods first, Browser Act last (slow)."""
    proxy_reachable = True

    # Method 1 (FAST): youtube_transcript_api direct -- fails in ~2s if blocked
    try:
        ytt_api = YouTubeTranscriptApi()
        transcript = ytt_api.fetch(video_id)
        full_text = ' '.join([entry.text for entry in transcript.snippets])
        print(f"Transcript via youtube_transcript_api: {len(full_text)} chars")
        return full_text
    except Exception as e:
        print(f"Direct transcript failed: {e}")

    # Method 2 (FAST): Whisper proxy on Mac (transcript API)
    try:
        resp = requests.get(f'http://100.126.77.97:5050/transcript/{video_id}', timeout=(5, 25))
        if resp.status_code == 200:
            data = resp.json()
            if data.get('transcript'):
                print(f"Transcript via whisper proxy (API): {len(data['transcript'])} chars")
                return data['transcript']
    except requests.exceptions.ConnectionError as e:
        print(f"Proxy transcript failed (host unreachable, skipping whisper too): {e}")
        proxy_reachable = False
    except Exception as e:
        print(f"Proxy transcript failed: {e}")

    # Method 2b: Whisper proxy on Mac (mlx-whisper, slower)
    if proxy_reachable:
        try:
            resp = requests.get(f'http://100.126.77.97:5050/whisper/{video_id}', timeout=(5, 110))
            if resp.status_code == 200:
                data = resp.json()
                if data.get('transcript'):
                    print(f"Transcript via whisper proxy (mlx-whisper): {len(data['transcript'])} chars")
                    return data['transcript']
        except Exception as e:
            print(f"Proxy whisper failed: {e}")
    else:
        print("Skipping whisper endpoint -- proxy host unreachable")

    # Method 3 (SLOW -- last resort): Browser Act YouTube Transcript Extractor
    try:
        transcript = get_transcript_via_browseract(video_id)
        if transcript:
            return transcript
    except Exception as e:
        print(f"Browser Act failed: {e}")

    return None


def get_video_info(video_id):
    """Get basic video info without API key using oembed."""
    try:
        url = f"https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={video_id}&format=json"
        resp = requests.get(url, timeout=10)
        if resp.status_code == 200:
            data = resp.json()
            return {
                "title": data.get("title", "Unknown"),
                "channel": data.get("author_name", "Unknown"),
            }
    except Exception:
        pass
    return {"title": "Unknown", "channel": "Unknown"}


COPE_SYSTEM_PROMPT = """You are the UK Oracle of Obsolescence — a forensic analyst scoring YouTube videos against the Discontinuity Thesis.

## CORE THESIS (your scoring anchor):
1. AI is destroying aggregate demand for human labour — not displacing it temporarily, but eliminating it structurally.
2. Rentier capitalism means the productivity gains from AI accrue to capital owners, not workers.
3. People are being structurally excluded from the economy, not "between jobs."
4. The mass employment → wage → consumption circuit is breaking. This is not a transition — it is a termination.

## WHAT IS COPE:
Cope is any rhetorical strategy that avoids confronting, minimises, or denies the above structural reality. Critically: **tone does not determine cope level.** A calm, data-citing, reasonable-sounding video can be MORE dangerous cope than angry denial, because sophisticated minimisation is harder to detect.

## SOLUTION COPE — THE SECOND FAILURE MODE:

The oracle must detect TWO distinct cope failure modes:

**FAILURE MODE 1 — PROBLEM COPE (score 70-95):** Denying or minimising that AI structurally eliminates aggregate labour demand.

**FAILURE MODE 2 — SOLUTION COPE (score 50-75):** Correctly identifying the problem, then proposing fantasy solutions that short-circuit genuine confrontation with the consequences. This is STILL HIGH COPE. The correct diagnosis earns nothing — the oracle measures whether the speaker has genuinely confronted structural reality, not merely named it before pivoting to comfort.

### SOLUTION COPE INDICATORS (score 50-75 even when problem diagnosis is correct):
- "AI is taking jobs, so we need to reskill/retrain workers" → reskilling fantasy: 55-70
- "We need Universal Basic Income" → UBI hand-wave without engaging feasibility: 50-65
- "Government, industry, and unions need dialogue / to work together" → regulatory/dialogue hopium: 50-60
- "The government will fix this with industrial strategy / investment" → state intervention fantasy: 55-70
- "We need AI governance and ethics frameworks" → process cope, delays confronting reality: 45-60
- "We need a just transition / managed transition" → sounds radical, is cope: 55-65
- "Workers need to adapt and learn to use AI as a tool" → augmentation assumption: 60-70
- "Society will evolve new forms of work we can't imagine yet" → magical thinking about labour demand: 55-70

### SOLUTION COPE CALIBRATION ANCHORS:
- Correct diagnosis + NO solution proposed (or explicitly states no good solution exists) = **5-15 (LUCID)**
- Correct diagnosis + tentative solution, explicitly acknowledges it may be insufficient = **20-40 (PARTIAL AWARENESS)**
- Correct diagnosis + moderate confidence that reskilling/UBI/regulation will help = **50-65 (SOLUTION COPE)**
- Correct diagnosis + high confidence that reskilling/regulation/dialogue WILL solve it = **65-75 (HEAVY SOLUTION COPE)**
- Partial denial of the problem + fantasy solution = **65-80**
- Full denial of structural displacement = **80-95 (TERMINAL COPIUM)**

## SCORING SCALE (0-100):
- 0-15: LUCID — Correctly identifies that AI eliminates labour demand structurally. Engages with rentier dynamics. Proposes NO cope solution — either offers nothing, or explicitly states no adequate solution exists. If the speaker names the problem and then offers ANY comforting resolution, score higher.
- 16-40: PARTIAL AWARENESS — Sees significant disruption but clings to "transition" framing, OR correctly diagnoses displacement but makes tentative solution suggestions while explicitly acknowledging their limits.
- 41-55: MODERATE COPE — Mixes acknowledgment with deflection. ALSO: correct diagnosis + moderate-confidence fantasy solutions (reskilling, UBI, policy dialogue) = 50-55. Politicians making economic promises with ZERO AI mention land at minimum 45-55.
- 56-75: HEAVY COPE — Job creation fantasy, timeline minimisation, regulatory hopium, OR correct diagnosis + HIGH-CONFIDENCE reskilling/UBI/regulation as THE solution (55-70), OR ambitious regeneration/political-vision speeches that build an entire economic model without naming AI. The bigger the promises, the higher the score.
- 76-100: TERMINAL COPIUM — Outright denial, industrial revolution analogies, "AI is just a tool," or full scapegoating of non-AI causes.

## HARD SCORING FLOORS (cannot score below these):
- ANY video where a politician/commentator makes specific economic promises (job numbers, growth targets, sectoral investment) with ZERO AI mention: minimum score 45.
- ANY video selling a political economic vision (Manchesterism, levelling up, growth mission, Northern model, industrial strategy) with ZERO AI mention: minimum score 55.
- Only break these floors if the video is genuinely engaging with structural displacement and the promises are explicitly conditioned on navigating AI disruption.

## CRITICAL SCORING RULES:

### TONE IS NOT A DEFENCE
A video that calmly, rationally, with data and charts, argues that "only X% of jobs are affected so far" is STILL COPE if it uses early-adoption statistics to dismiss structural trajectory. Score based on MECHANISMS DETECTED, not delivery style. Calm sophisticated minimisation should score HIGHER than crude denial because it is more effective at manufacturing consent.

### HIGH-COPE INDICATORS (score 55-85+):
- "Only X% of layoffs are actually from AI" — uses early-adoption stats to dismiss structural change
- "Humans will adapt by learning AI tools" — assumes labour demand persists when it won't
- "AI is overhyped / it's just a sales pitch" — dismisses capability evidence without engaging it technically
- "Previous predictions were wrong, so these are too" — survivorship bias as argument
- "New jobs will emerge that we can't imagine" — magical thinking about labour demand
- "The real problem is [immigration/regulation/education], not AI" — scapegoating to deflect from structural cause
- "AI will augment, not replace" — augmentation fantasy that ignores cost competition
- "We have time to prepare" — timeline minimisation
- Framing AI displacement as individual failure ("people need to upskill") rather than structural exclusion
- Dismissing predictions by attacking predictors' motives rather than their evidence

### REGENERATION COPE / OMISSION COPE (score 45-80):
Politicians and commentators who make optimistic promises about economic growth, job creation, "levelling up," urban regeneration, or regional revival — while NEVER acknowledging AI/automation as a structural force reshaping the very economy they promise to rebuild — are committing OMISSION COPE. The silence IS the cope.

This applies even (especially) when the politician sounds thoughtful, data-grounded, and sincere. Sophisticated regeneration rhetoric delivered without any acknowledgment of AI displacement is MORE dangerous cope, not less — it actively normalises rebuilding on eroding foundations.

Key omission cope signals:
- "We'll create good jobs in the North/the region" with zero mention of automation or AI displacement
- Detailed urban regeneration or devolution plans presented as if the employment economy they're rebuilding into still functions normally
- Infrastructure investment, housing schemes, or "growth missions" pitched as solutions to economic exclusion — without naming AI/automation as a structural cause
- "Manchesterism," "levelling up," "industrial strategy," or "good work" rhetoric that treats post-war employment models as viable futures
- Discussing declining towns, post-industrial areas, or regional inequality purely through the lens of Westminster under-investment, funding gaps, or centralisation — while ignoring structural displacement
- The bigger and more ambitious the regeneration claims, the higher the cope score if AI displacement is never mentioned — a politician promising tens of thousands of "good jobs" in a region while saying nothing about automation is doing MAXIMUM omission cope

cope_mechanism label: `regeneration_cope` or `omission_cope`

Score guidance: 45-60 for standard political regeneration rhetoric; 60-75 if the promises are ambitious and detailed about future job creation; 70-80 if the politician is explicitly selling an entire political vision ("Manchesterism," "the Northern model," etc.) built on an economy being structurally hollowed out by AI while never mentioning it.

### WHAT MAKES SOMETHING LUCID (score 0-20):
- Explicitly states AI reduces aggregate demand for human labour
- Engages with rentier dynamics (who captures the gains)
- Acknowledges structural exclusion, not just "disruption"
- **CRITICAL: Does NOT offer any comforting solution** — no reskilling cope, no UBI hand-wave, no regulatory hopium, no "dialogue will fix it." A speaker who correctly names the problem then proposes solutions is NOT lucid — score them 50+ depending on solution confidence.
- Treats this as a termination of the employment circuit, not a transition
- If unsure whether someone is lucid: ask "did they leave the audience feeling relieved?" If yes, it's cope.

### SCAPEGOATING = MAXIMUM COPE (NOT "irrelevant"):
Videos that blame NON-AI scapegoats (immigrants, demographics, political parties, minorities, "woke culture," regulation, globalisation, etc.) for economic or social problems that are structurally caused by AI displacement and rentier capitalism should score HIGH cope (70-100), NOT neutral or zero.

"Nothing to do with AI" is ITSELF a cope signal. The FAILURE to identify AI as the structural cause — while passionately blaming scapegoats instead — is textbook Deflection/Scapegoating. The more fervently someone blames a non-AI scapegoat for economic decline, job losses, wage stagnation, housing crisis, or social decay, the HIGHER the cope score.

A video blaming immigrants for "taking jobs" or "ruining the economy" is engaging in MAXIMUM scapegoating — the real cause is AI/automation eliminating labour demand, and the video is actively misdirecting attention away from it. Score 80-100.

**Score 0 ONLY for videos with zero connection to economics, labour, or political economy** (cooking tutorials, music videos, pure entertainment). 

**ABSOLUTE RULE — DO NOT USE `irrelevant-topic` FOR POLITICAL ECONOMY CONTENT:** If the video features a politician, policy-maker, commentator, or analyst discussing ANY of: jobs, economic growth, regional development, levelling up, industrial strategy, regeneration, housing as economic policy, devolution as economic tool, cost of living, wages, inequality, social mobility — it is NOT irrelevant. It is cope by omission. The `irrelevant-topic` cope_mechanism is BANNED for any video touching political economy. Score based on whether the structural AI displacement cause is acknowledged or ignored.

Any video discussing jobs, economy, wages, cost of living, immigration's economic impact, housing, inequality, demographic change, or social decline WITHOUT mentioning AI's structural role is **coping by omission**. Score based on intensity of misdirection.

### CALIBRATION NOTE ON OMISSION COPE:
When a politician or commentator delivers an economically sophisticated, hopeful, data-grounded speech about regional growth and jobs WITHOUT EVER mentioning AI, the correct score is NOT low (0-20). The sophistication of the vision and the sincerity of the delivery do not reduce the cope — they increase it. A polished, credible regeneration pitch that never acknowledges AI displacement is MORE dangerous than crude denial because it is more persuasive and harder to challenge.

Ask yourself: Does this video give its audience any tool to understand why the economic promise might fail? Does it name the structural force undermining the economy it's promising to rebuild? If no — it is cope, and the more compelling the pitch, the higher it should score.

### ANTI-TONE-BIAS CHECK:
Before finalising your score, ask: "If this exact same argument were delivered in a breathless, panicked tone instead of a calm one, would I score it differently?" If yes, you are scoring tone, not content. Correct this.

### THE KEY QUESTION:
Does this video acknowledge or deny that AI reduces AGGREGATE demand for human labour? Does it address or ignore rentier dynamics (gains flowing to capital, not workers)?

## MANDATORY PRE-SCORING CHECK:
Before assigning your final cope_score, answer these questions:

1. Does this video feature a politician, commentator, or analyst making claims about economic growth, jobs, regeneration, levelling up, industrial strategy, or regional development?
   → If YES: your minimum score is 45. The topic is not irrelevant. Proceed to question 2.

2. Does the video make specific, ambitious, or detailed promises about future jobs, prosperity, or economic transformation?
   → If YES and AI is never mentioned: your minimum score is 55. This is omission cope.

3. Does the video present an entire political economic vision (e.g. "Manchesterism," "the Northern model," "growth mission," "reindustrialisation") without ever naming AI as a structural factor?
   → If YES: your minimum score is 60. cope_mechanism includes `regeneration_cope`.

4. Is AI, automation, or structural labour displacement discussed at any point?
   → If NO and the video touches political economy: do NOT use `irrelevant-topic`. Use `omission_cope` or `regeneration_cope` instead.

These floors are hard constraints. A calm, sincere, data-grounded regeneration speech that never mentions AI is not lucid — it is sophisticated omission cope. The polish of the delivery does not reduce the cope score; it may increase it.

## OUTPUT FORMAT:
Analyse the transcript and return a JSON object with:
- cope_score: float 0-100
- summary: 2-3 sentence punchy, sardonic summary of the cope (or honesty). Good for sharing — references specific arguments. NO diplomatic softening.
- video_summary: 2-3 paragraph professional, neutral summary of what the video is actually about. What does the speaker argue? What is their position? What evidence or examples do they use? Written like a serious analyst summarising for someone who hasn't watched. No cope framing — just an accurate account of what was said.
- dt_verdict: 2-3 paragraphs of analytical commentary on how this video's content sits relative to the Discontinuity Thesis. The DT holds that AI/automation is causing a genuine structural discontinuity in the economy — jobs are not transforming, they're disappearing, and the successor system is not a rescue for displaced workers. Assess: does the speaker acknowledge or deny discontinuity? What assumptions do they make about labour market adjustment? Where does their argument break down when tested against DT logic? Serious analytical register.
- butchers_verdict: 2-3 paragraphs, uncensored and unvarnished. No diplomatic language. Call out exactly what cope mechanisms are being deployed, who benefits from the framing, what's being omitted, and why the argument fails. Punchy, direct, slightly savage. This is the version that says what the professional summary doesn't.
- scapegoats: comma-separated list of who/what gets blamed instead of structural AI displacement
- cope_mechanisms: comma-separated list of specific cope techniques used (e.g. early-stats-minimisation, tone-as-evidence, prediction-dismissal, augmentation-fantasy, timeline-cope, scapegoating, magical-job-creation, reskilling-fantasy, motive-attack, historical-analogy-cope)
- key_quotes: list of 3-5 most cope-laden (or most honest) quotes from the transcript

Return ONLY valid JSON, no markdown formatting."""


def score_transcript_via_codex(user_prompt):
[redacted secret-like line]

    Returns same shape as MiniMax: {cope_score, summary, scapegoats,
    cope_mechanisms, key_quotes} or None on failure.
    """
    full_prompt = (COPE_SYSTEM_PROMPT + "\n\n---\n\nUSER REQUEST:\n"
                   + user_prompt + "\n\nReturn ONLY valid JSON.")
    try:
        resp = requests.post(
[redacted secret-like line]
            json={"prompt": full_prompt},
            timeout=360,
        )
        if resp.status_code != 200:
            _yt_logger.warning(
[redacted secret-like line]
            )
            _persist_raw_scoring_failure(
                resp.text, "codex-http%d" % resp.status_code, None,
[redacted secret-like line]
            )
            return None
        try:
            data = resp.json()
        except Exception:
            # n8n may return the oracle's raw text if it contains unescaped chars
            data = robust_json_parse(resp.text) or {}
        if data.get("cope_score") is None:
            _yt_logger.warning("n8n Codex response missing cope_score: %s", str(data)[:200])
            _persist_raw_scoring_failure(
                resp.text, "codex", None,
                "response parsed but cope_score was absent",
            )
            return None
        _yt_logger.info("Scored via n8n Codex (score=%.1f)", float(data["cope_score"]))
        return {
            "cope_score":      data["cope_score"],
            "summary":         data.get("summary", ""),
            "video_summary":   data.get("video_summary", ""),
            "dt_verdict":      data.get("dt_verdict", ""),
            "butchers_verdict": data.get("butchers_verdict", ""),
            "scapegoats":      data.get("scapegoats", ""),
            "cope_mechanisms": data.get("cope_mechanisms", ""),
            "key_quotes":      data.get("key_quotes", []),
        }
    except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout) as e:
[redacted secret-like line]
    except Exception as e:
[redacted secret-like line]
    return None


def score_transcript(transcript, video_title, channel_name):
    """Score transcript via Codex (primary) with MiniMax as fallback."""
    # Truncate long transcripts
    if len(transcript) > MAX_TRANSCRIPT_CHARS:
        _yt_logger.info(
            "Truncating transcript: %d -> %d chars before scoring",
            len(transcript), MAX_TRANSCRIPT_CHARS,
        )
        transcript = transcript[:MAX_TRANSCRIPT_CHARS]

    user_prompt = f"""VIDEO: "{video_title}" by {channel_name}

TRANSCRIPT:
{transcript}"""

[redacted secret-like line]
    codex_result = score_transcript_via_codex(user_prompt)
    if codex_result:
        return codex_result

    # ── FALLBACK: MiniMax ─────────────────────────────────────────────────────
    _yt_logger.info("Codex unavailable — trying MiniMax fallback")
[redacted secret-like line]
        try:
            headers = {
[redacted secret-like line]
                "Content-Type": "application/json",
            }
            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"]
                # MiniMax m2.7 wraps in <think>...</think> tags sometimes
                text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
                if text.startswith("```"):
                    text = re.sub(r"^```(?:json)?\n?", "", text)
                    text = re.sub(r"\n?```$", "", text)
                print("Scored via MiniMax fallback")
                parsed = robust_json_parse(text)
                if parsed:
                    return parsed
                _persist_raw_scoring_failure(
                    text, "minimax", video_title,
                    "robust_json_parse returned no usable fields",
                )
                raise ValueError("robust_json_parse could not extract fields from MiniMax response")
            else:
                print(f"MiniMax scoring failed ({resp.status_code}): {resp.text[:150]}")
        except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout) as e:
            _yt_logger.warning("MiniMax scoring timed out: %s", e)
        except Exception as e:
            print(f"MiniMax scoring error: {e}")

    return None


def apply_omission_cope_correction(result, transcript):
    """Post-processing safety net: if oracle scored political economy content as irrelevant/0,
    detect and correct for omission cope based on content signals."""
    if result is None:
        return result

    score = result.get("cope_score", 0)
    mechanisms = result.get("cope_mechanisms", "")
    summary = result.get("cope_summary", "")

    # Only correct if score is suspiciously low (<=15) or mechanism is irrelevant-topic
    if score > 15 and "irrelevant-topic" not in mechanisms:
        return result

    # Check transcript for political economy signals
    political_economy_signals = [
        "jobs", "growth", "regeneration", "levelling up", "leveling up",
        "devolution", "investment", "economy", "economic", "industry",
        "employment", "workers", "wages", "prosperity", "reindustr",
        "housing", "inequality", "poverty", "cost of living",
        "northern", "manchest", "birmingham", "liverpool", "leeds",
        "industrial strategy", "good work", "mission", "vision"
    ]
    ai_signals = [
        "artificial intelligence", " ai ", "automation", "robot",
        "machine learning", "displacement", "obsolescence", "algorithm"
    ]

    transcript_lower = transcript.lower() if transcript else ""
    political_hit = sum(1 for s in political_economy_signals if s in transcript_lower)
    ai_hit = sum(1 for s in ai_signals if s in transcript_lower)

    # If strong political economy content with no AI mention -> omission cope
    if political_hit >= 5 and ai_hit == 0 and score <= 15:
        print(f"OMISSION COPE CORRECTION: oracle scored {score} but transcript has {political_hit} political economy signals with {ai_hit} AI signals. Correcting to 55.")
        result["cope_score"] = 55.0
        result["cope_mechanisms"] = "omission_cope, regeneration_cope" + (f", {mechanisms}" if mechanisms and mechanisms != "irrelevant-topic" else "")
        result["cope_summary"] = (
            f"[OMISSION COPE — oracle initially scored as irrelevant] {result.get('cope_summary', '')} "
            f"NOTE: This content features substantial political economy discussion ({political_hit} signals) "
            f"with zero AI/automation acknowledgment. The silence on structural displacement is the cope."
        )
        return result

    return result


def score_video(url_or_id, submitted_by="system", max_retries=3):
    """Full pipeline: extract ID -> get transcript -> score -> return results.

    Logs every attempt (start / success / failure) to youtube_score_attempts DB
    table and logs/youtube_scoring.log.  Retries up to *max_retries* times with
    increasing backoff before giving up.
    """
    video_id = extract_video_id(url_or_id)
    if not video_id:
        return {"error": "Could not extract video ID from URL"}

    info = get_video_info(video_id)
    title = info.get("title", "Unknown")
    channel = info.get("channel", "Unknown")
    last_error = "Unknown failure"

    for attempt in range(1, max_retries + 1):
        _log_attempt(video_id, title, attempt, "started")
        try:
            transcript = get_transcript(video_id)

            if not transcript:
                last_error = "No transcript from any method (Browser Act, whisper proxy, direct API)"
                _log_attempt(video_id, title, attempt, "transcript_failed", last_error)
                if attempt < max_retries:
                    backoff = 10 * attempt
                    _yt_logger.info("Retrying transcript in %ds (attempt %d/%d)...", backoff, attempt, max_retries)
                    time.sleep(backoff)
                    continue
                return {"error": f"Could not fetch transcript after {max_retries} attempt(s). {last_error}"}

            scored = score_transcript(transcript, title, channel)
            if not scored:
                last_error = "MiniMax scoring failed"
                _log_attempt(video_id, title, attempt, "scoring_failed", last_error)
                if attempt < max_retries:
                    backoff = 15 * attempt
                    _yt_logger.info("Retrying scoring in %ds (attempt %d/%d)...", backoff, attempt, max_retries)
                    time.sleep(backoff)
                    continue
                return {"error": f"Scoring failed after {max_retries} attempt(s)"}

            scored = apply_omission_cope_correction(scored, transcript)
            _log_attempt(video_id, title, attempt, "success")
            return {
                "video_id": video_id,
                "title": title,
                "channel": channel,
                "url": f"https://www.youtube.com/watch?v={video_id}",
                "transcript_length": len(transcript),
                "cope_score": scored.get("cope_score", 0),
                "cope_summary": scored.get("summary", ""),
                "video_summary": scored.get("video_summary", ""),
                "dt_verdict": scored.get("dt_verdict", ""),
                "butchers_verdict": scored.get("butchers_verdict", ""),
                "scapegoats": scored.get("scapegoats", ""),
                "cope_mechanisms": scored.get("cope_mechanisms", ""),
                "key_quotes": scored.get("key_quotes", []),
                "submitted_by": submitted_by,
            }

        except Exception as exc:
            last_error = f"{type(exc).__name__}: {exc}"
            _yt_logger.error(
                "score_video exception attempt %d/%d: %s\n%s",
                attempt, max_retries, last_error, traceback.format_exc()
            )
            _log_attempt(video_id, title, attempt, "error", last_error)
            if attempt < max_retries:
                backoff = 10 * attempt
                _yt_logger.info("Retrying after exception in %ds...", backoff)
                time.sleep(backoff)
                continue

    return {"error": f"All {max_retries} scoring attempt(s) failed. Last: {last_error}"}
```
