---
type: "Source File"
title: "\"\"\""
description: "\"\"\" oracle_commentary.py — Generate DT 3.3 Oracle Commentary for data.copecheck.com Uses MiniMax M2.7 (primary, free) with Gemini Gemma-4-31b fallback. Scores each country+series combo against the Discontinuity Thesis."
resource: "https://data.copecheck.com"
tags: ["copecheck", "data", "source-file", "py"]
timestamp: "2026-09-25T21:31:44Z"
site: "data"
source_path: "copecheck-data/oracle_commentary.py"
---

# """

Source path: `copecheck-data/oracle_commentary.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-25T21:31:44Z`

```py
"""
oracle_commentary.py — Generate DT 3.3 Oracle Commentary for data.copecheck.com

Uses MiniMax M2.7 (primary, free) with Gemini Gemma-4-31b fallback.
Scores each country+series combo against the Discontinuity Thesis v3.3 framework.

Usage:
    python3 oracle_commentary.py              # Score all countries × key series
    python3 oracle_commentary.py --series youth_unemployment --country ES
    python3 oracle_commentary.py --batch 5    # Score 5 random unscored combos
"""

import os
import sys
import json
import re
import time
import random
import logging
import argparse
import requests
from pathlib import Path

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import db

LOG_DIR = Path(__file__).parent / "logs"
LOG_DIR.mkdir(exist_ok=True)
logging.basicConfig(
    filename=str(LOG_DIR / "oracle.log"),
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger(__name__)

# ─── API Config ───
[redacted secret-like line]
MINIMAX_URL = "https://api.minimax.io/v1/chat/completions"
MINIMAX_MODEL = "minimax-m2.7"

[redacted secret-like line]
GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it:generateContent"

COUNTRY_NAMES = {
    "US": "United States", "UK": "United Kingdom", "DE": "Germany",
    "FR": "France", "ES": "Spain", "IT": "Italy", "NL": "Netherlands",
    "SE": "Sweden", "PL": "Poland", "EU": "EU-27",
}

SERIES_NAMES = {
    "youth_unemployment": "Youth Unemployment (15-24)",
    "labour_share_gdp": "Labour Share of GDP",
    "gdp_growth": "GDP Growth Rate",
    "employment_ratio": "Employment Ratio",
    "labour_force_participation": "Labour Force Participation",
    "neet_rate": "NEET Rate (Youth)",
    "gini_index": "Gini Index",
    "industry_employment_share": "Industry Employment Share",
    "services_employment_share": "Services Employment Share",
}

# Key series to prioritise for commentary
KEY_SERIES = ["youth_unemployment", "labour_share_gdp", "employment_ratio", "neet_rate", "gdp_growth"]

# ─── DT 3.3 Oracle Prompt ───
DT33_SYSTEM = """You are the CopeCheck Oracle, an economic analyst applying the Discontinuity Thesis v3.3 framework to real labour market data.

The Discontinuity Thesis v3.3 holds that AI automation creates a structural break — not a gradual transition — in labour markets. It identifies four key tests:

1. **Unit-Cost Collision** (weight 30%): Whether AI dramatically undercuts human labour costs in the relevant sector. Score 0-100.
2. **Interface Collapse** (weight 25%): Whether the integration layer protecting human workers (credentials, tacit knowledge, client relationships) is dissolving. Score 0-100.
3. **Propagation Blindness** (weight 25%): Whether policymakers, institutions, and public discourse are failing to recognise or prepare for the speed/scale of displacement. Score 0-100.
4. **Coordination Feasibility** (weight 20%): Whether realistic policy coordination could prevent mass displacement (inverse — high score means coordination is unlikely). Score 0-100.

COPE SCORING:
- 0-20: "reality" — data reflects genuine engagement with displacement dynamics
- 21-40: "somewhat-lucid" — partial recognition but significant blind spots
- 41-60: "partial-cope" — acknowledges some issues but fundamentally underestimates scale
- 61-80: "heavy-cope" — significant denial of structural forces
- 81-100: "pure-cope" — complete detachment from displacement realities

CRITICAL PRINCIPLE: Redistribution (UBI, sovereign wealth, dividend funds) is system replacement, not system rescue. It preserves consumption while conceding production. Score accordingly — these don't "solve" displacement, they manage transition to a different system.

COMMENTARY STRUCTURE: Your commentary_md MUST be structured into three clearly labelled sections:
(a) **What the data shows** — Describe the trend, level, and any notable movements in the indicator. Reference specific values and dates.
(b) **What it means for the thesis** — Apply the DT 3.3 framework. Does this data support, contradict, or complicate the discontinuity hypothesis? Be specific about which of the four tests are most relevant.
(c) **Counterarguments and caveats** — Steel-man the opposing view. What alternative explanations exist? What data limitations or confounding factors should the reader consider? Where might the DT 3.3 lens be overfitting?

You MUST respond with valid JSON only. No markdown, no explanation outside JSON."""

def build_prompt(series_id, country, data_points):
    """Build the scoring prompt with real data context."""
    series_name = SERIES_NAMES.get(series_id, series_id)
    country_name = COUNTRY_NAMES.get(country, country)

    # Format data points
    data_str = "\n".join([
        f"  {p['date']}: {p['value']:.2f}%" for p in data_points
    ]) if data_points else "  No historical data available"

    latest = data_points[0] if data_points else None
    latest_str = f"{latest['value']:.2f}% ({latest['date']})" if latest else "N/A"

    return f"""Analyse this economic indicator through the DT 3.3 framework:

INDICATOR: {series_name}
COUNTRY: {country_name} ({country})
LATEST VALUE: {latest_str}

HISTORICAL DATA (most recent first):
{data_str}

Score this data point against all four DT 3.3 tests. Consider:
- What does this indicator reveal about the structural position of human labour?
- Is this trend consistent with approaching discontinuity or stability?
- How does the current level compare to what the DT 3.3 model would predict?

Respond with this exact JSON structure:
{{
    "headline": "Short punchy headline (max 12 words)",
    "commentary_md": "3-paragraph analysis in markdown structured as: (a) What the data shows, (b) What it means for the thesis, (c) Counterarguments and caveats. Reference specific data values.",
    "scores": {{
        "unit_cost_collision": <0-100>,
        "interface_collapse": <0-100>,
        "propagation_blindness": <0-100>,
        "coordination_feasibility": <0-100>
    }},
    "cope_score": <weighted average 0-100>,
    "cope_type": "<reality|somewhat-lucid|partial-cope|heavy-cope|pure-cope>",
    "verdict": "One sentence DT 3.3 verdict"
}}"""


def strip_think_tags(text):
    """Strip MiniMax <think>...</think> reasoning tags."""
    match = re.search(r'</think>', text)
    if match:
        text = text[match.end():].strip()
    return text


def extract_json(text):
    """Extract JSON from response text, handling markdown code blocks."""
    text = strip_think_tags(text)
    # Try to find JSON in code blocks
    m = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', text, re.DOTALL)
    if m:
        return m.group(1)
    # Try raw JSON
    m = re.search(r'\{.*\}', text, re.DOTALL)
    if m:
        return m.group(0)
    return text


def call_minimax(system_prompt, user_prompt):
    """Call MiniMax M2.7 API."""
    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}
                ],
[redacted secret-like line]
                "temperature": 0.7
            },
            timeout=30
        )
        if resp.status_code == 200:
            data = resp.json()
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            if content:
                return content, "minimax-m2.7"
            log.warning(f"MiniMax empty response: {data}")
        else:
            log.warning(f"MiniMax HTTP {resp.status_code}: {resp.text[:200]}")
    except Exception as e:
        log.error(f"MiniMax error: {e}")
    return None, None


def call_gemini(system_prompt, user_prompt):
    """Call Gemini Gemma-4-31b as fallback."""
    try:
        resp = requests.post(
            f"{GEMINI_URL}?key={GEMINI_KEY}",
            headers={"Content-Type": "application/json"},
            json={
                "system_instruction": {"parts": [{"text": system_prompt}]},
                "contents": [{"parts": [{"text": user_prompt}]}],
                "generationConfig": {
[redacted secret-like line]
                    "temperature": 0.7
                }
            },
            timeout=30
        )
        if resp.status_code == 200:
            data = resp.json()
            content = data.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "")
            if content:
                return content, "gemma-4-31b"
            log.warning(f"Gemini empty response: {data}")
        else:
            log.warning(f"Gemini HTTP {resp.status_code}: {resp.text[:200]}")
    except Exception as e:
        log.error(f"Gemini error: {e}")
    return None, None


def score_indicator(series_id, country):
    """Score a single indicator+country combo."""
    # Get historical data
    data_points = db.get_series_data(series_id, country=country, limit=20)
    if not data_points:
        log.warning(f"No data for {series_id}/{country}")
        return None

    prompt = build_prompt(series_id, country, data_points)

    # Try MiniMax first, then Gemini
    raw, model = call_minimax(DT33_SYSTEM, prompt)
    if not raw:
        log.info(f"MiniMax failed for {series_id}/{country}, trying Gemini...")
        time.sleep(1)
        raw, model = call_gemini(DT33_SYSTEM, prompt)
    if not raw:
        log.error(f"All models failed for {series_id}/{country}")
        return None

    # Parse JSON
    try:
        json_str = extract_json(raw)
        result = json.loads(json_str)
    except (json.JSONDecodeError, Exception) as e:
        log.error(f"JSON parse failed for {series_id}/{country}: {e}\nRaw: {raw[:500]}")
        return None

    # Validate required fields
    required = ["headline", "commentary_md", "cope_score", "cope_type"]
    for field in required:
        if field not in result:
            log.error(f"Missing field '{field}' in response for {series_id}/{country}")
            return None

    # Compute weighted score if sub-scores provided
    scores = result.get("scores", {})
    if scores:
        weighted = (
            scores.get("unit_cost_collision", 50) * 0.30 +
            scores.get("interface_collapse", 50) * 0.25 +
            scores.get("propagation_blindness", 50) * 0.25 +
            scores.get("coordination_feasibility", 50) * 0.20
        )
        result["cope_score"] = round(weighted, 1)

    # Validate cope_type against computed score
    score = result["cope_score"]
    if score >= 80:
        result["cope_type"] = "pure-cope"
    elif score >= 60:
        result["cope_type"] = "heavy-cope"
    elif score >= 40:
        result["cope_type"] = "partial-cope"
    elif score >= 20:
        result["cope_type"] = "somewhat-lucid"
    else:
        result["cope_type"] = "reality"

    # Store in DB
    snapshot = json.dumps({
        "data_points": data_points[:5],
        "scores": scores,
        "verdict": result.get("verdict", "")
    })

    with db.conn() as c:
        c.execute("""
            INSERT INTO oracle_commentary
            (series_id, country, trigger_type, headline, commentary_md,
             cope_score, cope_type, data_snapshot, model)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            series_id, country, "scheduled",
            result["headline"], result["commentary_md"],
            result["cope_score"], result["cope_type"],
            snapshot, model
        ))

    log.info(f"Scored {series_id}/{country}: {result['cope_type']} ({result['cope_score']})")
    print(f"  ✓ {country}/{series_id}: {result['headline']} [{result['cope_type']} {result['cope_score']}] via {model}")
    return result


def get_unscored_combos():
    """Get country+series combos that haven't been scored yet."""
    all_combos = []
    for series_id in KEY_SERIES:
        countries = db.get_countries_for_series(series_id)
        for c in countries:
            all_combos.append((series_id, c))

    # Check which already have commentary
    existing = set()
    with db.conn() as c:
        rows = c.execute("SELECT series_id, country FROM oracle_commentary").fetchall()
        for r in rows:
            existing.add((r["series_id"], r["country"]))

    return [(s, c) for s, c in all_combos if (s, c) not in existing]


def run_batch(batch_size=None):
    """Score a batch of unscored combos."""
    unscored = get_unscored_combos()
    if not unscored:
        print("All key series+country combos have been scored!")
        return

    if batch_size:
        random.shuffle(unscored)
        unscored = unscored[:batch_size]

    print(f"Scoring {len(unscored)} combos...")
    success = 0
    for series_id, country in unscored:
        print(f"Scoring {COUNTRY_NAMES.get(country, country)} — {SERIES_NAMES.get(series_id, series_id)}...")
        result = score_indicator(series_id, country)
        if result:
            success += 1
        time.sleep(2)  # Rate limiting

    print(f"\nDone: {success}/{len(unscored)} scored successfully")


def main():
    parser = argparse.ArgumentParser(description="Generate DT 3.3 Oracle Commentary")
    parser.add_argument("--series", help="Specific series ID to score")
    parser.add_argument("--country", help="Specific country code to score")
    parser.add_argument("--batch", type=int, help="Score N random unscored combos")
    parser.add_argument("--all", action="store_true", help="Score all unscored combos")
    args = parser.parse_args()

    db.init()

    if args.series and args.country:
        result = score_indicator(args.series, args.country.upper())
        if result:
            print(json.dumps(result, indent=2))
    elif args.batch:
        run_batch(args.batch)
    elif args.all:
        run_batch()
    else:
        # Default: score 10 unscored combos
        run_batch(10)


if __name__ == "__main__":
    main()
```
