---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Fill missing three-layer oracle fields (video_summary, dt_verdict, butchers_verdict, scapegoats) on scored YouTube videos. Two modes: * No args - hourly cron safety net. Picks up to."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-09-19T21:58:07Z"
site: "uk"
source_path: "copecheck-uk/oracle_backfill.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/oracle_backfill.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-19T21:58:07Z`

```py
#!/usr/bin/env python3
"""Fill missing three-layer oracle fields (video_summary, dt_verdict,
butchers_verdict, scapegoats) on scored YouTube videos.

Two modes:
  * No args   - hourly cron safety net. Picks up to MAX_PER_CRON_RUN recent
                videos that are still missing the extended fields.
  * With args - targeted:  oracle_backfill.py VIDEO_ID [VIDEO_ID ...]
                Fired immediately (async) by app.py once the cc-node-01 worker
                delivers a core score, so the extended pass lands in seconds.

Transcript source order:
  1. transcript stored on the row (sent by the worker via /score-complete)
  2. the existing fetch routes in youtube_scorer (YouTube API / proxy /
     Browser Act) - kept as fallbacks, never removed.
Any transcript fetched here is written back to the row so later passes and
re-runs never have to hit YouTube again (the VPS IP is datacenter-blocked).

Safety: the extended pass can only ADD to a row. It writes video_summary,
dt_verdict, butchers_verdict and (only when empty) scapegoats. It never
touches cope_score, cope_summary, cope_mechanisms, key_quotes or scored_at -
those belong to the initial MiniMax pass, which is the authoritative score.
"""
import fcntl
import json
import os
import sqlite3
import sys
from datetime import datetime, timedelta, timezone

sys.path.insert(0, "/home/ben/infra/copecheck-uk")
import youtube_scorer as ys
import db_uk as db

LOG = "/home/ben/infra/copecheck-uk/logs/oracle_backfill.log"
DB = "/home/ben/infra/copecheck-uk/data/copecheck_uk.db"
MAX_PER_CRON_RUN = 3
LOCK_DIR = "/tmp"

SELECT_COLS = (
    "video_id, title, channel, cope_score, cope_summary, scapegoats, "
    "cope_mechanisms, key_quotes, transcript_length"
)


def log(msg):
    line = f"{datetime.now()}: {msg}"
    try:
        with open(LOG, "a") as f:
            f.write(line + "\n")
    except Exception:
        pass
    print(line)


def connect():
    conn = sqlite3.connect(DB, timeout=30)
    conn.row_factory = sqlite3.Row
    return conn


def has_transcript_column(conn):
    return "transcript" in [r[1] for r in conn.execute("PRAGMA table_info(youtube_videos)")]


def select_rows(video_ids):
    """Return (rows, has_transcript_column). Degrades if migration not applied."""
    conn = connect()
    has_tr = has_transcript_column(conn)
    tcol = "transcript" if has_tr else "NULL AS transcript"
    if video_ids:
        placeholders = ",".join("?" * len(video_ids))
        rows = conn.execute(
            f"SELECT {SELECT_COLS}, {tcol} FROM youtube_videos "
            f"WHERE video_id IN ({placeholders}) AND cope_score IS NOT NULL",
            video_ids,
        ).fetchall()
    else:
        cutoff = (datetime.now(timezone.utc) - timedelta(days=14)).strftime("%Y-%m-%d %H:%M:%S")
        rows = conn.execute(
            f"""SELECT {SELECT_COLS}, {tcol} FROM youtube_videos
                WHERE (video_summary IS NULL OR video_summary = '' OR video_summary = '0')
                  AND cope_score IS NOT NULL
                  AND scored_at >= ?
                ORDER BY scored_at DESC LIMIT ?""",
            (cutoff, MAX_PER_CRON_RUN),
        ).fetchall()
    conn.close()
    return rows, has_tr


def cache_transcript(video_id, text):
    """Persist a freshly fetched transcript so we never refetch it."""
    try:
        conn = connect()
        conn.execute(
            "UPDATE youtube_videos SET transcript = ? WHERE video_id = ?", (text, video_id)
        )
        conn.commit()
        conn.close()
        log(f"  {video_id}: cached transcript ({len(text)} chars)")
    except Exception as exc:
        log(f"  {video_id}: could not cache transcript: {exc}")


def pick(new_value, old_value):
    """Prefer a non-empty new value, otherwise keep what is already stored."""
    if new_value is None:
        return old_value if old_value is not None else ""
    if isinstance(new_value, str) and not new_value.strip():
        return old_value if old_value is not None else ""
    return new_value


def process(row, has_tr):
    vid = row["video_id"]
    title = row["title"] or "Unknown"
    channel = row["channel"] or "Unknown"
    log(f"  {vid}: {title[:60]}")

    transcript = (row["transcript"] or "") if has_tr else ""
    source = "stored"

    if not transcript:
        source = "fetched"
        try:
            transcript = ys.get_transcript(vid) or ""
        except Exception as exc:
            log(f"  {vid}: transcript fetch error: {exc}")
            transcript = ""
        if transcript and has_tr:
            cache_transcript(vid, transcript)

    if not transcript:
        log(f"  {vid}: no transcript (none stored, all fetch routes failed) - skipping")
        return False

    log(f"  {vid}: using {source} transcript ({len(transcript)} chars)")

    result = ys.score_transcript(transcript[: ys.MAX_TRANSCRIPT_CHARS], title, channel)
    if not result:
        log(f"  {vid}: oracle returned None - core score left untouched")
        return False

    vs = result.get("video_summary", "") or ""
    dt = result.get("dt_verdict", "") or ""
    bv = result.get("butchers_verdict", "") or ""
    if not vs and not dt and not bv:
        log(f"  {vid}: still no three-layer fields after rescore - core score left untouched")
        return False

    # --- ADDITIVE ONLY [redacted]
    # The initial scoring pass (MiniMax, via the cc-node-01 worker) owns
    # cope_score, cope_summary, cope_mechanisms and key_quotes. Codex is
    # non-deterministic (repeat passes on one video returned 28/64/22/53), so
    # letting it revise those made the published number partly noise.
    # The extended pass may only ADD narrative fields, and may fill scapegoats
    # only where the initial pass left it empty.
    scapegoats_add = None
    if not (row["scapegoats"] or "").strip():
        cand = result.get("scapegoats", "")
        if isinstance(cand, str) and cand.strip():
            scapegoats_add = cand

    db.add_youtube_extended_fields(
        video_id=vid,
        video_summary=vs,
        dt_verdict=dt,
        butchers_verdict=bv,
        scapegoats=scapegoats_add,
    )
    log(
        f"  {vid}: SAVED extended fields (vs={len(vs)}ch dt={len(dt)}ch "
        f"bv={len(bv)}ch scapegoats="
        f"{'set' if scapegoats_add else 'unchanged'}); cope_score preserved at "
        f"{row['cope_score']} (codex suggested {result.get('cope_score')})"
    )
    return True


def process_locked(row, has_tr):
    """Serialise per-video so the instant trigger and the cron never collide."""
    vid = row["video_id"]
    lock_path = os.path.join(LOCK_DIR, f"oracle-ext-{vid}.lock")
    try:
        fh = open(lock_path, "w")
    except Exception:
        return process(row, has_tr)
    try:
        try:
            fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            log(f"  {vid}: extended pass already running elsewhere - skipping")
            return False
        return process(row, has_tr)
    finally:
        try:
            fh.close()
        except Exception:
            pass


def main():
    video_ids = [a.strip() for a in sys.argv[1:] if a.strip()]
    rows, has_tr = select_rows(video_ids)
    if not rows:
        return 0
    mode = "targeted" if video_ids else "cron sweep"
    log(f"Extended oracle pass ({mode}): {len(rows)} video(s)")
    done = 0
    for row in rows:
        try:
            if process_locked(row, has_tr):
                done += 1
        except Exception as exc:
            log(f"  {row['video_id']}: ERROR {exc}")
    log(f"Extended oracle pass complete: {done}/{len(rows)} filled")
    return 0


if __name__ == "__main__":
    sys.exit(main())
```
