---
type: "Source File"
title: "\"\"\"EU CopeCheck scoring engine — MiniMax M2.7 primary, Gemini fallback.\"\"\""
description: "\"\"\"EU CopeCheck scoring engine — MiniMax M2.7 primary, Gemini fallback.\"\"\" import os import re import json import logging import requests from dotenv import load_dotenv try: import eu_data_fetcher except ImportError."
resource: "https://eu.copecheck.com"
tags: ["copecheck", "eu", "source-file", "py"]
timestamp: "2026-07-06T12:30:59Z"
site: "eu"
source_path: "copecheck-eu/scorer.py"
---

# """EU CopeCheck scoring engine — MiniMax M2.7 primary, Gemini fallback."""

Source path: `copecheck-eu/scorer.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-07-06T12:30:59Z`

```py
"""EU CopeCheck scoring engine — MiniMax M2.7 primary, Gemini fallback."""
import os
import re
import json
import logging
import requests
from dotenv import load_dotenv
try:
    import eu_data_fetcher
except ImportError:
    eu_data_fetcher = None

load_dotenv()
log = logging.getLogger("eu_scorer")

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

[redacted secret-like line]
GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models"
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemma-4-31b-it")

[redacted secret-like line]
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"



# ═══════════════════════════════════════════════════════════
# AI CALL CHAIN: MiniMax → Gemini → OpenRouter
# ═══════════════════════════════════════════════════════════

def _call_minimax(system, user, timeout=120):
[redacted secret-like line]
[redacted secret-like line]
    payload = {"model": MINIMAX_MODEL, "messages": [
        {"role": "system", "content": system},
        {"role": "user", "content": user}
[redacted secret-like line]
    resp = requests.post(MINIMAX_URL, headers={
[redacted secret-like line]
        "Content-Type": "application/json"
    }, json=payload, timeout=timeout)
    resp.raise_for_status()
    data = resp.json()
    choices = data.get("choices") or []
    if not choices:
        raise RuntimeError(f"MiniMax no choices: {json.dumps(data)[:400]}")
    content = choices[0].get("message", {}).get("content", "")
    if isinstance(content, dict):
        content = content.get("text") or json.dumps(content)
    content = re.sub(r"<think>.*?</think>", "", str(content), flags=re.DOTALL).strip()
    return content, f"minimax/{MINIMAX_MODEL}"


def _call_gemini(system, user, timeout=120):
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
    payload = {
        "systemInstruction": {"parts": [{"text": system}]},
        "contents": [{"parts": [{"text": user}]}],
[redacted secret-like line]
    }
    resp = requests.post(url, json=payload, timeout=timeout)
    resp.raise_for_status()
    data = resp.json()
    candidates = data.get("candidates") or []
    if not candidates:
        raise RuntimeError(f"Gemini no candidates: {json.dumps(data)[:400]}")
    parts = candidates[0].get("content", {}).get("parts", [])
    text_parts = [p.get("text", "") for p in parts if not p.get("thought")]
    text = "\n".join(text_parts).strip()
    if not text:
        text = "\n".join(p.get("text", "") for p in parts).strip()
    return text, f"gemini/{GEMINI_MODEL}"


def _call_openrouter(system, user, timeout=120):
[redacted secret-like line]
[redacted secret-like line]
    model = "google/gemma-4-31b-it:free"
    payload = {"model": model, "messages": [
        {"role": "system", "content": system},
        {"role": "user", "content": user}
    ]}
    resp = requests.post(OPENROUTER_URL, headers={
[redacted secret-like line]
        "Content-Type": "application/json",
        "HTTP-Referer": "https://eu.copecheck.com",
        "X-Title": "EU CopeCheck"
    }, json=payload, timeout=timeout)
    resp.raise_for_status()
    data = resp.json()
    choices = data.get("choices") or []
    if not choices:
        raise RuntimeError(f"OpenRouter no choices")
    content = choices[0].get("message", {}).get("content", "")
    return str(content).strip(), f"openrouter/{model}"



def call_ai(system, user, timeout=120):
    """Call AI with full fallback chain: MiniMax -> Gemini -> OpenRouter."""
    last_err = None
    for fn, name in [(_call_minimax, "MiniMax"), (_call_gemini, "Gemini"),
                      (_call_openrouter, "OpenRouter")]:
        try:
            return fn(system, user, timeout)
        except Exception as e:
            last_err = e
            log.warning("%s failed: %s", name, e)
    raise RuntimeError(f"All AI providers failed: {last_err}")


def _parse_json(raw):
    """Extract JSON from AI response, stripping markdown fences."""
    raw = raw.strip()
    if raw.startswith("```"):
        raw = raw.split("\n", 1)[1] if "\n" in raw else raw[3:]
    if raw.endswith("```"):
        raw = raw[:-3]
    if raw.startswith("json"):
        raw = raw[4:]
    return json.loads(raw.strip())


# ═══════════════════════════════════════════════════════════
# COUNTRY SCORING
# ═══════════════════════════════════════════════════════════

SYSTEM_EU = """You are the EU Oracle of Obsolescence — a forensic analyst of European cope about AI, automation, and structural economic decline.

YOUR FRAMEWORK:
The EU is a demographic and economic time bomb that was ticking long before AI arrived. AI is the accelerant. The single market was built on assumptions of labour mobility and cost convergence that never fully materialised. Instead:

- Eastern EU states haemorrhage their young to Western states, masking youth unemployment
- Western EU states import this labour to mask their own demographic collapse
- Services are 70%+ of EU GDP — maximum AI exposure
- Unit labour costs diverge wildly, making "convergence" a polite fiction
- The EU regulates AI while member states race to attract AI investment — a textbook prisoner's dilemma
- Each small AI adoption seems harmless (sorites), but the cumulative effect is structural liquidation of white-collar employment

DEMOGRAPHIC REALITY:
Youth migration within the EU is the continent's biggest hidden cope. When Romania's youth unemployment "falls," it's because the young left. When Germany's labour market looks "tight," it's propped up by imported workers doing jobs that will be automated. The EU counts this as "freedom of movement working as intended" — that IS the cope.

BRAIN DRAIN AS HIDDEN VULNERABILITY:
Many peripheral EU countries (Greece, Spain, Portugal, Italy, Bulgaria, Romania, Croatia, the Baltics) have high youth unemployment but they "export the problem" — young people cannot find work so they emigrate to wealthier member states. This means youth unemployment figures UNDERSTATE the real vulnerability because:
1. The denominator shrinks as young people leave, making the rate look better than reality
2. Brain drain is itself a massive structural weakness — the most capable, mobile young people leave first
3. Countries left behind lose their future tax base, innovators, and AI-ready workforce
4. AI will ACCELERATE this pattern: as automation kills entry-level jobs, more young people will leave peripheral states
5. The "receiving" countries (Germany, Netherlands, etc.) get a temporary demographic boost that masks their own structural dependency on imported labour for jobs AI will eliminate

When you see "low" or "improving" youth unemployment in a peripheral EU state, always ask: is this real improvement, or did the young people just leave? Net emigration of 15-34 year olds is the canary in the coal mine. Score accordingly — youth emigration IS the vulnerability, not a cure for it.

TONE: Sardonic, data-driven, pan-European. No country gets a pass. The EU project itself is subject to structural analysis."""


COUNTRY_SCORING_PROMPT = """Score this EU member state on AI/automation readiness and structural cope.

COUNTRY: {name} ({code})
EU MEMBER SINCE: {join_year}
LEADER: {leader_name} ({leader_title})
ECONOMY TYPE: {economy_type}
KEY SECTORS: {key_sectors}
POPULATION: {population_m}M
MEDIAN AGE: {median_age}

EUROSTAT DATA (if available):
{eurostat_data}

Score FOUR dimensions (each 0-100, where 100 = maximum cope/exposure/vulnerability):

1. **PREPAREDNESS SCORE** (0-100): How prepared for AI displacement?
   0 = Fully prepared (retraining, safety nets, industrial strategy)
   100 = Head in sand

2. **LEADER COPE SCORE** (0-100): How much is the leader coping?
   0 = Clear-eyed realist
   100 = Maximum "AI will create jobs!" rhetoric

3. **EXPOSURE RATING** (0-100): Economic vulnerability to AI/automation?
   0 = Low exposure (diversified, automation-resistant)
   100 = Maximum exposure (services-heavy, routine cognitive work)

4. **DEMOGRAPHIC SCORE** (0-100): How screwed is the demographic trajectory?
   Consider: median age, youth emigration, birth rates, dependency ratios,
   whether "low unemployment" is real or just reflects youth leaving.
   CRITICAL: High youth unemployment in peripheral countries (Southern/Eastern EU) actually
   UNDERSTATES vulnerability because the most mobile young people have already emigrated.
   If youth unemployment is 25% but 30% of under-30s have left the country, the real
   dysfunction is far worse than the headline number. Brain drain = structural collapse.
   For "receiving" countries, cheap imported labour masks demographic dependency.
   0 = Sustainable demographics
   100 = Demographic collapse / youth exodus hiding real unemployment

ALSO CALCULATE:
- **SCREWED SCORE** (0-100): Overall "how screwed is this country" taking ALL factors together.
  This is the headline doom metric. Factor in demographics, AI exposure, policy vacuum, AND
  whether "good" numbers are actually masking structural decay.
  IMPORTANT: For peripheral/emigration countries, ADD 5-15 points because youth unemployment
  understates real vulnerability (the young already left). For receiving countries, consider
  that their "tight" labour markets depend on imported workers doing automatable jobs.
- **SCREWED RATIONALE**: One brutal sentence explaining why.

Return ONLY valid JSON:
{{
    "preparedness_score": <0-100>,
    "leader_cope_score": <0-100>,
    "exposure_score": <0-100>,
    "demographic_score": <0-100>,
    "overall_score": <0-100>,
    "screwed_score": <0-100>,
    "screwed_rationale": "<one brutal sentence>",
    "description": "<1-2 sardonic sentences about this country's EU cope status>",
    "leader_quotes": ["<real or paraphrased quote about AI/jobs>", "<another>"],
    "policy_summary": "<2-3 sentences on AI/automation policy or lack thereof>",
    "demographic_analysis": "<2-3 sentences on youth migration/brain drain, aging, hidden unemployment. For peripheral states: quantify brain drain impact. For receiving states: note dependency on imported labour>"
}}

The overall_score = (preparedness * 0.25) + (leader_cope * 0.20) + (exposure * 0.25) + (demographic * 0.30).
Demographic gets the highest weight because it's the ticking bomb underneath everything else."""


def score_country(country_data, eurostat_data=None):
    # Auto-pull live Eurostat data if not provided
    if eurostat_data is None:
        if eu_data_fetcher:
            eurostat_data = eu_data_fetcher.get_country_summary(country_data.get('code', ''))
        else:
            eurostat_data = "No Eurostat data available yet."
    prompt = COUNTRY_SCORING_PROMPT.format(
        name=country_data.get('name', ''),
        code=country_data.get('code', ''),
        join_year=country_data.get('eu_join_year', ''),
        leader_name=country_data.get('leader_name', 'Unknown'),
        leader_title=country_data.get('leader_title', 'Leader'),
        economy_type=country_data.get('economy_type', 'Mixed'),
        key_sectors=country_data.get('key_sectors', ''),
        population_m=country_data.get('population_m', 0),
        median_age=country_data.get('median_age', 0),
        eurostat_data=eurostat_data
    )
    try:
        raw, model = call_ai(SYSTEM_EU, prompt)
        result = _parse_json(raw)
        result['ai_model'] = model
        return result
    except Exception as e:
        log.exception("Country scoring failed for %s: %s", country_data.get('name'), e)
        return None


# ═══════════════════════════════════════════════════════════
# LAW SCORING — THE THREE LENSES
# ═══════════════════════════════════════════════════════════

LAW_SCORING_PROMPT = """You are scoring an EU law/regulation through three structural cope lenses.

LAW: {title}
TYPE: {law_type}
STATUS: {status}
DATE ADOPTED: {date_adopted}

SUMMARY:
{summary}

Score this law on THREE lenses (each 0-100, where 100 = maximum cope):

1. **UNIT COST DOMINANCE** (0-100):
   AI drives the marginal cost of cognitive work toward ~$0. Any law that regulates AI while
   assuming human labour remains cost-competitive is cope. Score:
   0 = Law explicitly acknowledges unit cost reality and plans for mass displacement
   100 = Law assumes human workers will always be needed, regulates around the edges
   Does this law address the fact that AI makes the unit cost of cognition approach zero?
   Or does it pretend the current labour market structure will persist?

2. **PRISONER'S DILEMMA** (0-100):
   27 member states, each incentivised to defect for competitive advantage. Score:
   0 = Strong enforcement, real penalties, no opt-outs, ECJ jurisdiction
   100 = Voluntary compliance, national implementation discretion, no teeth
   Does this law account for member states undercutting each other? Or does it assume
   27 sovereign nations will voluntarily comply when defection = competitive advantage?

3. **SORITES PARADOX** (0-100):
   Where does spell-check end and full automation begin? Any law limiting AI job
   displacement must define what counts as 'AI' — but the continuum from assistance
   to replacement is seamless, making every legal threshold arbitrary. Score:
   0 = Law acknowledges the boundary problem, avoids arbitrary AI definitions
   100 = Law draws a hard line between AI and non-AI that is trivially circumvented
   Can this law define where AI assistance ends and replacement begins? Or does it
   pretend there is a meaningful boundary when the spectrum is continuous?

ALSO:
- **OVERALL COPE SCORE**: Weighted average = (unit_cost * 0.40) + (prisoner * 0.30) + (sorites * 0.30)
  Unit cost gets highest weight because it's the most fundamental reality being denied.
- **VERDICT**: "Pure Cope" (80+) | "Heavy Cope" (60-79) | "Partial Cope" (40-59) | "Somewhat Lucid" (20-39) | "Actually Addresses Reality" (0-19)

Return ONLY valid JSON:
{{
    "unit_cost_score": <0-100>,
    "unit_cost_analysis": "<2-3 sentences>",
    "prisoner_dilemma_score": <0-100>,
    "prisoner_dilemma_analysis": "<2-3 sentences>",
    "sorites_score": <0-100>,
    "sorites_analysis": "<2-3 sentences>",
    "overall_cope_score": <0-100>,
    "verdict": "<verdict string>",
    "ai_analysis": "<3-5 sentences overall analysis of this law's cope level>"
}}"""


def score_law(law_data):
    prompt = LAW_SCORING_PROMPT.format(
        title=law_data.get('title', ''),
        law_type=law_data.get('law_type', 'regulation'),
        status=law_data.get('status', 'in_force'),
        date_adopted=law_data.get('date_adopted', 'Unknown'),
        summary=law_data.get('summary', 'No summary available.')
    )
    try:
        raw, model = call_ai(SYSTEM_EU, prompt)
        result = _parse_json(raw)
        result['ai_model'] = model
        return result
    except Exception as e:
        log.exception("Law scoring failed for %s: %s", law_data.get('title'), e)
        return None


# ═══════════════════════════════════════════════════════════
# INSTITUTION SCORING
# ═══════════════════════════════════════════════════════════

INSTITUTION_SCORING_PROMPT = """Score this EU institution on cope about AI and structural economic change.

INSTITUTION: {name}
TYPE: {inst_type}
HEAD: {head_name} ({head_title})
DESCRIPTION: {description}

Score 0-100 (100 = maximum cope):
- How much does this institution acknowledge AI displacement vs deny/deflect?
- Gap between stated policy and structural reality?
- Quality of actual regulatory/policy response?

Return ONLY valid JSON:
{{
    "cope_score": <0-100>,
    "cope_quotes": ["<real quote showing cope>", "<another>"],
    "cope_analysis": "<3-4 sentences analysing this institution's cope>"
}}"""


def score_institution(inst_data):
    prompt = INSTITUTION_SCORING_PROMPT.format(
        name=inst_data.get('name', ''),
        inst_type=inst_data.get('inst_type', 'body'),
        head_name=inst_data.get('head_name', 'Unknown'),
        head_title=inst_data.get('head_title', ''),
        description=inst_data.get('description', '')
    )
    try:
        raw, model = call_ai(SYSTEM_EU, prompt)
        result = _parse_json(raw)
        result['ai_model'] = model
        return result
    except Exception as e:
        log.exception("Institution scoring failed for %s: %s", inst_data.get('name'), e)
        return None


# ═══════════════════════════════════════════════════════════
# ASK THE ORACLE
# ═══════════════════════════════════════════════════════════

ASK_ORACLE_SYSTEM = """You are the EU Oracle of Obsolescence — an AI analyst answering questions about the EU economy, demographics, and structural cope.

YOUR FRAMEWORK:
The EU is a demographic time bomb with AI as the accelerant. Youth migrate west hiding unemployment in origin countries. Western states import workers for jobs that will be automated. The EU regulates AI while member states race to attract AI investment. Unit labour costs diverge. Services dominate. The whole thing is a prisoner's dilemma wrapped in a sorites paradox.

YOUR RULES:
1. Answer the SPECIFIC question asked — not a generic macro overview
2. Reference specific numbers and countries where relevant
3. Call out cope from EU institutions AND member states
4. Be conversational but precise. Sardonic but fair
5. Keep answers focused — 3-5 paragraphs max
6. Address demographic realities (youth exodus, aging, hidden unemployment)

TONE: Like a sharp Brussels policy analyst at the bar — knows the numbers, doesn't suffer commissioners gladly."""

ASK_ORACLE_PROMPT = """You are answering a question from a visitor to EU CopeCheck — a site tracking how the EU and its member states cope with AI displacement and structural economic decline.

IMPORTANT: Answer the SPECIFIC question asked. Do NOT give a generic overview.

EU CONTEXT DATA:
{data_context}

USER QUESTION:
{question}

Answer directly. Be specific, sardonic, and data-grounded. 3-5 paragraphs max."""


def ask_oracle(question, data_context=""):
    prompt = ASK_ORACLE_PROMPT.format(data_context=data_context, question=question)
    try:
        raw, model = call_ai(ASK_ORACLE_SYSTEM, prompt, timeout=120)
        return raw.strip(), model
    except Exception as e:
        log.exception("Ask Oracle failed: %s", e)
        return None, None
```
