---
type: "Source File"
title: "\"\"\"Rescore all UK videos with new prompt - direct whisper proxy + MiniMax\"\"\""
description: "\"\"\"Rescore all UK videos with new prompt - direct whisper proxy + MiniMax\"\"\" import sys, os, time, json, sqlite3, requests, re sys.path.insert(0, '/home/ben/infra/copecheck-uk') from dotenv import load_dotenv."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-05-10T12:43:43Z"
site: "uk"
source_path: "copecheck-uk/rescore_v2.py"
---

# """Rescore all UK videos with new prompt - direct whisper proxy + MiniMax"""

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

```py
"""Rescore all UK videos with new prompt - direct whisper proxy + MiniMax"""
import sys, os, time, json, sqlite3, requests, re
sys.path.insert(0, '/home/ben/infra/copecheck-uk')

from dotenv import load_dotenv
load_dotenv('/home/ben/infra/copecheck-uk/.env')

[redacted secret-like line]
MINIMAX_URL = 'https://api.minimax.io/v1/chat/completions'
MINIMAX_MODEL = 'minimax-m2.7'
WHISPER_PROXY = 'http://100.126.77.97:5050'
DB_PATH = '/home/ben/infra/copecheck-uk/data/copecheck_uk.db'

from youtube_scorer import COPE_SYSTEM_PROMPT

def get_transcript_robust(video_id, max_retries=2):
    for attempt in range(max_retries):
        try:
            resp = requests.get(f'{WHISPER_PROXY}/transcript/{video_id}', timeout=(10, 30))
            if resp.status_code == 200:
                data = resp.json()
                if data.get('transcript'):
                    return data['transcript']
        except Exception as e:
            print(f'    Transcript API attempt {attempt+1} failed: {e}')
        try:
            resp = requests.get(f'{WHISPER_PROXY}/whisper/{video_id}', timeout=(10, 180))
            if resp.status_code == 200:
                data = resp.json()
                if data.get('segments'):
                    return ' '.join(s['text'].strip() for s in data['segments'])
                elif data.get('transcript'):
                    return data['transcript']
        except Exception as e:
            print(f'    Whisper attempt {attempt+1} failed: {e}')
        if attempt < max_retries - 1:
            print(f'    Retrying in 15s...')
            time.sleep(15)
    return None

def extract_json_from_response(text):
    """Try multiple strategies to extract JSON from LLM response."""
    # Strip think tags
    text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
    # Strip markdown code blocks
    if text.startswith('```'):
        text = re.sub(r'^```(?:json)?\n?', '', text)
        text = re.sub(r'\n?```$', '', text)
    # Try direct parse
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        pass
    # Try to find JSON object in the text
    match = re.search(r'\{[^{}]*"cope_score"[^{}]*\}', text, re.DOTALL)
    if match:
        try:
            return json.loads(match.group())
        except json.JSONDecodeError:
            pass
    # Try finding any JSON object
    for m in re.finditer(r'\{[^{}]+\}', text):
        try:
            obj = json.loads(m.group())
            if 'cope_score' in obj:
                return obj
        except json.JSONDecodeError:
            continue
    # Last resort: find cope_score with regex
    score_match = re.search(r'"cope_score"\s*:\s*(\d+(?:\.\d+)?)', text)
    summary_match = re.search(r'"summary"\s*:\s*"([^"]*)"', text)
    if score_match:
        return {
            'cope_score': float(score_match.group(1)),
            'summary': summary_match.group(1) if summary_match else 'Parse error - score extracted via regex',
            'scapegoats': '',
            'cope_mechanisms': '',
            'key_quotes': []
        }
    return None

def score_with_minimax(transcript, title, channel, retries=2):
    user_prompt = f'VIDEO: "{title}" by {channel}\n\nTRANSCRIPT:\n{transcript[:100000]}'
    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},
        ],
[redacted secret-like line]
        'temperature': 0.7,
    }
    for attempt in range(retries):
        try:
            resp = requests.post(MINIMAX_URL, headers=headers, json=payload, timeout=120)
            if resp.status_code == 200:
                text = resp.json()['choices'][0]['message']['content']
                result = extract_json_from_response(text)
                if result:
                    return result
                else:
                    print(f'    JSON parse failed (attempt {attempt+1}), raw: {text[:200]}')
            else:
                print(f'    MiniMax HTTP {resp.status_code} (attempt {attempt+1})')
        except Exception as e:
            print(f'    MiniMax error (attempt {attempt+1}): {e}')
        if attempt < retries - 1:
            time.sleep(5)
    return None

# Main
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('SELECT video_id, title, cope_score, channel FROM youtube_videos')
videos = c.fetchall()

print(f'Rescoring {len(videos)} videos with updated Discontinuity Thesis prompt')
print(f'Using: Whisper proxy + MiniMax ({MINIMAX_MODEL})')
print('=' * 80)

results = []
success_count = 0
fail_count = 0

for i, v in enumerate(videos):
    vid_id = v['video_id']
    old_score = v['cope_score'] if v['cope_score'] is not None else 0
    title = v['title']
    channel = v['channel']

    print(f'\n[{i+1}/{len(videos)}] {title[:65]}')
    print(f'  Channel: {channel} | Old score: {old_score}')

    try:
        transcript = get_transcript_robust(vid_id)
        if not transcript:
            print(f'  FAILED: Could not get transcript')
            results.append({'video_id': vid_id, 'title': title, 'old_score': old_score, 'new_score': None, 'error': 'no transcript'})
            fail_count += 1
            time.sleep(5)
            continue

        print(f'  Transcript: {len(transcript)} chars')

        result = score_with_minimax(transcript, title, channel)
        if not result:
            print(f'  FAILED: MiniMax scoring failed')
            results.append({'video_id': vid_id, 'title': title, 'old_score': old_score, 'new_score': None, 'error': 'scoring failed'})
            fail_count += 1
            time.sleep(5)
            continue

        new_score = float(result.get('cope_score', 0))
        summary = str(result.get('summary', ''))
        scapegoats = result.get('scapegoats', '')
        mechanisms = result.get('cope_mechanisms', '')
        key_quotes = result.get('key_quotes', [])

        if isinstance(scapegoats, list): scapegoats = ', '.join(str(x) for x in scapegoats)
        if isinstance(mechanisms, list): mechanisms = ', '.join(str(x) for x in mechanisms)
        if isinstance(key_quotes, list): key_quotes = json.dumps(key_quotes)
        if isinstance(summary, list): summary = '; '.join(str(x) for x in summary)

        c.execute('''UPDATE youtube_videos
                     SET cope_score = ?, cope_summary = ?, scapegoats = ?,
                         cope_mechanisms = ?, key_quotes = ?, scored_at = CURRENT_TIMESTAMP
                     WHERE video_id = ?''',
                  (new_score, str(summary), str(scapegoats), str(mechanisms), str(key_quotes), vid_id))
        conn.commit()

        delta = new_score - old_score
        print(f'  NEW SCORE: {new_score:.0f} (was {old_score:.0f}, delta {delta:+.0f})')
        print(f'  {str(summary)[:120]}')
        results.append({'video_id': vid_id, 'title': title, 'old_score': old_score, 'new_score': new_score})
        success_count += 1

    except Exception as e:
        print(f'  EXCEPTION: {e}')
        results.append({'video_id': vid_id, 'title': title, 'old_score': old_score, 'new_score': None, 'error': str(e)[:50]})
        fail_count += 1

    if i < len(videos) - 1:
        time.sleep(8)

conn.close()

print('\n\n' + '=' * 80)
print(f'RESCORE COMPLETE: {success_count} succeeded, {fail_count} failed')
print('=' * 80)
print(f'{"Video":<55} {"Old":>5} {"New":>5} {"D":>5}')
print('-' * 75)
for r in results:
    t = r['title'][:52] + '...' if len(r['title']) > 52 else r['title']
    old = r['old_score'] if r['old_score'] else 0
    if r['new_score'] is not None:
        print(f'{t:<55} {old:>5.0f} {r["new_score"]:>5.0f} {r["new_score"]-old:>+5.0f}')
    else:
        print(f'{t:<55} {old:>5.0f} {"FAIL":>5} {r.get("error","")}')
```
