---
type: "Source File"
title: "\"\"\"Retry failed videos from rescore run\"\"\""
description: "\"\"\"Retry failed videos from rescore run\"\"\" 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-10T13:25:28Z"
site: "uk"
source_path: "copecheck-uk/rescore_retry.py"
---

# """Retry failed videos from rescore run"""

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

```py
"""Retry failed videos from rescore run"""
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')
from youtube_scorer import COPE_SYSTEM_PROMPT

[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'

FAILED_VIDEOS = [
    ('37HGgQWtIvU', '2025: What ACTUALLY Happened? w/ Ash Sarkar & Aaron Bastani', 'Novara Media', 38.5),
    ('XV_B96fAzKs', 'Steven Bartlett sharing harmful health misinformation in Diary of CEO podcast | BBC News', 'BBC News', 85.0),
    ('DlXOn-VE5AI', 'Steven Bartlett: The AI Revolution is a Lie: Here\'s the Dark Truth | Karen Hao', 'Journey of a Visionary', 28.5),
]

def extract_json_from_response(text):
    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)
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        pass
    match = re.search(r'\{[^{}]*"cope_score"[^{}]*\}', text, re.DOTALL)
    if match:
        try:
            return json.loads(match.group())
        except:
            pass
    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 'Score extracted via regex',
            'scapegoats': '', 'cope_mechanisms': '', 'key_quotes': []
        }
    return None

def get_transcript(video_id):
    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:
        pass
    try:
        resp = requests.get(f'{WHISPER_PROXY}/whisper/{video_id}', timeout=(10, 300))
        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 failed: {e}')
    return None

conn = sqlite3.connect(DB_PATH)
c = conn.cursor()

for vid_id, title, channel, old_score in FAILED_VIDEOS:
    print(f'\nRetrying: {title[:60]}')
    transcript = get_transcript(vid_id)
    if not transcript:
        print(f'  Still no transcript - skipping')
        continue
    print(f'  Got transcript: {len(transcript)} chars')

    user_prompt = f'VIDEO: "{title}" by {channel}\n\nTRANSCRIPT:\n{transcript[:100000]}'
[redacted secret-like line]
    payload = {
        'model': MINIMAX_MODEL,
        'messages': [
            {'role': 'system', 'content': COPE_SYSTEM_PROMPT},
            {'role': 'user', 'content': user_prompt},
        ],
[redacted secret-like line]
    }
    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:
                new_score = float(result.get('cope_score') or 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)
                c.execute('''UPDATE youtube_videos
                     SET cope_score = ?, cope_summary = ?, scapegoats = ?,
                         cope_mechanisms = ?, key_quotes = ?, scored_at = CURRENT_TIMESTAMP
                     WHERE video_id = ?''',
                  (new_score, summary, str(scapegoats), str(mechanisms), str(key_quotes), vid_id))
                conn.commit()
                print(f'  NEW SCORE: {new_score:.0f} (was {old_score:.0f}, delta {new_score-old_score:+.0f})')
                print(f'  {summary[:100]}')
            else:
                print(f'  JSON parse failed')
        else:
            print(f'  MiniMax error: {resp.status_code}')
    except Exception as e:
        print(f'  Error: {e}')
    time.sleep(10)

conn.close()
print('\nRetry complete!')
```
