---
type: "Source File"
title: "\"\"\"YouTube Cope Scorer v2 - downloads audio + Whisper transcription + MiniMax scoring.\"\"\""
description: "\"\"\"YouTube Cope Scorer v2 - downloads audio + Whisper transcription + MiniMax scoring.\"\"\" import os import re import json import subprocess import tempfile import requests from datetime import datetime [redacted."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-06-02T12:58:43Z"
site: "uk"
source_path: "copecheck-uk/youtube_scorer_v2.py"
---

# """YouTube Cope Scorer v2 - downloads audio + Whisper transcription + MiniMax scoring."""

Source path: `copecheck-uk/youtube_scorer_v2.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-06-02T12:58:43Z`

```py
"""YouTube Cope Scorer v2 - downloads audio + Whisper transcription + MiniMax scoring."""
import os
import re
import json
import subprocess
import tempfile
import requests
from datetime import datetime

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

# Whisper model - "base" is fast on CPU, "small" is better quality
WHISPER_MODEL = os.environ.get("WHISPER_MODEL", "base")
_whisper_model = None


def _get_whisper():
    global _whisper_model
    if _whisper_model is None:
        from faster_whisper import WhisperModel
        print(f"Loading Whisper model '{WHISPER_MODEL}'...")
        _whisper_model = WhisperModel(
            WHISPER_MODEL, device="cpu", compute_type="int8"
        )
        print("Whisper loaded.")
    return _whisper_model


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"^([a-zA-Z0-9_-]{11})$",
    ]
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    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"}


def download_audio(video_id):
    """Download audio from YouTube video using yt-dlp. Returns path to audio file."""
    tmp_dir = tempfile.mkdtemp(prefix="yt_cope_")
    output_path = os.path.join(tmp_dir, "audio.%(ext)s")
    try:
        result = subprocess.run([
            "yt-dlp",
            "--extract-audio",
            "--audio-format", "mp3",
            "--audio-quality", "5",
            "--no-playlist",
            "--quiet",
            "-o", output_path,
            f"https://www.youtube.com/watch?v={video_id}"
        ], capture_output=True, text=True, timeout=120)
        if result.returncode != 0:
            print(f"  yt-dlp error: {result.stderr[:200]}")
            return None
        # Find the downloaded file
        for f in os.listdir(tmp_dir):
            if f.startswith("audio"):
                return os.path.join(tmp_dir, f)
        return None
    except subprocess.TimeoutExpired:
        print("  yt-dlp timed out")
        return None
    except Exception as e:
        print(f"  yt-dlp exception: {e}")
        return None


def transcribe_audio(audio_path):
    """Transcribe audio file using faster-whisper."""
    try:
        model = _get_whisper()
        segments, info = model.transcribe(audio_path, beam_size=5)
        print(f"  Language: {info.language} (prob {info.language_probability:.2f})")
        full_text = " ".join(seg.text.strip() for seg in segments)
        return full_text
    except Exception as e:
        print(f"  Whisper error: {e}")
        return None


def get_transcript(video_id):
    """Download video audio and transcribe with Whisper."""
    print(f"  Downloading audio...")
    audio_path = download_audio(video_id)
    if not audio_path:
        return None
    print(f"  Transcribing with Whisper ({WHISPER_MODEL})...")
    transcript = transcribe_audio(audio_path)
    # Cleanup
    try:
        import shutil
        shutil.rmtree(os.path.dirname(audio_path), ignore_errors=True)
    except Exception:
        pass
    return transcript


def score_transcript(transcript, video_title, channel_name):
    """Send transcript to MiniMax for cope scoring."""
[redacted secret-like line]
[redacted secret-like line]
        return None

    system_prompt = """You are the UK Oracle of Obsolescence — a forensic analyst of British political and economic cope.

Score this YouTube video transcript for COPE content. Cope is defined as: deflection, scapegoating, denial of structural problems, magical thinking about solutions, or any rhetorical strategy that avoids confronting uncomfortable economic/political realities.

Analyse the transcript and return a JSON object with:
- cope_score: float 0-100 (0 = brutally honest, 100 = weapons-grade cope)
- summary: 2-3 sentence summary of the cope (or honesty) in this video. Sardonic, punchy tone.
- scapegoats: comma-separated list of who/what gets blamed
- cope_mechanisms: comma-separated list of specific cope techniques used (e.g. "appeal to tradition", "false equivalence", "magical job creation", "reskilling fantasy", "blame immigrants", "blame boomers", "both sides", "it will be fine")
- key_quotes: list of 3-5 most cope-laden (or most honest) quotes from the transcript

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

    user_prompt = f'VIDEO: "{video_title}" by {channel_name}\n\nTRANSCRIPT:\n{transcript[:15000]}'

    try:
        resp = requests.post(MINIMAX_URL, headers={
[redacted secret-like line]
            "Content-Type": "application/json"
        }, json={
            "model": MINIMAX_MODEL,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ],
            "temperature": 0.7,
[redacted secret-like line]
        }, timeout=90)
        if resp.status_code != 200:
            print(f"  MiniMax error: {resp.status_code} {resp.text[:200]}")
            return None
        text = resp.json()["choices"][0]["message"]["content"]
        text = text.strip()
        # Strip MiniMax think tags
        think_match = re.search(r'</think>', text)
        if think_match:
            text = text[think_match.end():].strip()
        # Strip markdown code fences
        if text.startswith("```"):
            text = re.sub(r"^```(?:json)?\n?", "", text)
            text = re.sub(r"\n?```$", "", text)
        # Extract JSON
        json_match = re.search(r'\{[\s\S]*\}', text)
        if not json_match:
            print(f"  No JSON found in response: {text[:200]}")
            return None
        return json.loads(json_match.group())
    except json.JSONDecodeError as e:
        print(f"  JSON parse error: {e}")
        print(f"  Raw text: {text[:300]}")
        return None
    except Exception as e:
        print(f"  MiniMax scoring error: {e}")
        return None


def score_video(url_or_id, submitted_by="user"):
    """Full pipeline: extract ID -> download -> whisper -> score -> return."""
    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)
    transcript = get_transcript(video_id)
    if not transcript:
        return {"error": "Could not download or transcribe video."}

    result = score_transcript(transcript, info["title"], info["channel"])
    if not result:
        return {"error": "Scoring failed — MiniMax API error"}

    return {
        "video_id": video_id,
        "title": info["title"],
        "channel": info["channel"],
        "url": f"https://www.youtube.com/watch?v={video_id}",
        "transcript_length": len(transcript),
        "cope_score": result.get("cope_score", 0),
        "cope_summary": result.get("summary", ""),
        "scapegoats": result.get("scapegoats", ""),
        "cope_mechanisms": result.get("cope_mechanisms", ""),
        "key_quotes": result.get("key_quotes", []),
        "submitted_by": submitted_by,
    }
```
