---
type: "Source File"
title: "\"\"\"Countries CopeCheck — Flask app scoring countries on AI/automation cope.\"\"\""
description: "\"\"\"Countries CopeCheck — Flask app scoring countries on AI/automation cope.\"\"\" import os import json import re import hashlib import markdown import requests as http_requests from flask import Flask, render_template."
resource: "https://countries.copecheck.com"
tags: ["copecheck", "countries", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "countries"
source_path: "copecheck-countries/app.py"
---

# """Countries CopeCheck — Flask app scoring countries on AI/automation cope."""

Source path: `copecheck-countries/app.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-26T08:28:11Z`

```py
"""Countries CopeCheck — Flask app scoring countries on AI/automation cope."""

import os
import json
import re
import hashlib
import markdown
import requests as http_requests
from flask import Flask, render_template, abort, request, jsonify
from dotenv import load_dotenv
from db import (init_db, init_history, get_leaderboard, get_country, get_country_count,
                get_archive, get_archive_count, get_country_by_name,
                get_history_months, get_history_for_month, get_country_history,
                upsert_country, check_rate_limit, record_rate_limit,
                get_leaderboard_paginated, get_archive_paginated,
                get_history_for_month_paginated, get_system_freshness)

load_dotenv()

app = Flask(__name__)


# ── Trailing-slash canonicalisation (consolidated 20260926T082811Z, infra sweep) ──
# Single shared implementation; see slash_canonical.py. Revert by deleting
# these two lines and slash_canonical.py.
from slash_canonical import install_slash_canonicaliser  # noqa: E402
install_slash_canonicaliser(app)  # noqa: E402


[redacted secret-like line]

PORT = int(os.getenv('COUNTRIES_PORT', 8099))

PER_PAGE = 20

def paginate_args():
    """Extract page number from query string."""
    try:
        page = int(request.args.get('page', 1))
        return max(1, page)
    except (ValueError, TypeError):
        return 1


[redacted secret-like line]
MINIMAX_URL = "https://api.minimax.io/v1/chat/completions"
MINIMAX_MODEL = "minimax-m2.7"
CAPTCHA_ANSWERS = {"7", "seven"}
COUNTRY_SCORING_ENABLED = os.getenv('COUNTRY_SCORING_ENABLED', '').strip().lower() in {
    '1', 'true', 'yes', 'on'
}


def cope_color(score):
    if score is None:
        return 'cope-moderate'
    s = float(score)
    if s < 25:
        return 'cope-lucid'
    elif s < 45:
        return 'cope-partial'
    elif s < 60:
        return 'cope-moderate'
    elif s < 78:
        return 'cope-heavy'
    return 'cope-terminal'


def cope_label(score):
    if score is None:
        return 'UNSCORED'
    s = float(score)
    if s < 25:
        return 'LUCID'
    elif s < 45:
        return 'PARTIAL COPE'
    elif s < 60:
        return 'MODERATE COPE'
    elif s < 78:
        return 'HEAVY COPE'
    return 'TERMINAL COPE'


def screwed_color(score):
    if score is None:
        return 'screwed-moderate'
    s = float(score)
    if s < 30:
        return 'screwed-low'
    elif s < 50:
        return 'screwed-moderate'
    elif s < 70:
        return 'screwed-high'
    return 'screwed-terminal'


def screwed_label(score):
    if score is None:
        return 'UNKNOWN'
    s = float(score)
    if s < 30:
        return 'CUSHIONED'
    elif s < 50:
        return 'EXPOSED'
    elif s < 70:
        return 'VULNERABLE'
    return 'PROPERLY SCREWED'


def parse_quotes(quotes_str):
    if not quotes_str:
        return []
    try:
        return json.loads(quotes_str)
    except (json.JSONDecodeError, TypeError):
        return []


def render_md(text):
    if not text:
        return ''
    return markdown.markdown(text)


app.jinja_env.filters['copecolor'] = cope_color
app.jinja_env.filters['copelabel'] = cope_label
app.jinja_env.filters['screwedcolor'] = screwed_color
app.jinja_env.filters['screwedlabel'] = screwed_label
def screwed_verdict(policy_text):
    """Extract a short screwed explanation from policy_summary."""
    if not policy_text:
        return ""
    text = policy_text.strip()
    # Take first sentence or first 200 chars
    for end in ['. ', '! ', '? ']:
        idx = text.find(end)
        if idx > 0 and idx < 250:
            return text[:idx+1]
    if len(text) > 200:
        return text[:197].rsplit(" ", 1)[0] + "..."
    return text

app.jinja_env.filters['screwedverdict'] = screwed_verdict

app.jinja_env.filters['parse_quotes'] = parse_quotes
app.jinja_env.filters['render_md'] = render_md


def render_verdict(text):
    """Render text that might contain markdown fragments, stripping stray ** and ## artifacts."""
    if not text:
        return ''
    # Convert markdown bold **text** to <strong>
    text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
    # Convert markdown headers ## Header to styled text
    text = re.sub(r'^#{1,4}\s+(.+)$', r'<strong>\1</strong>', text, flags=re.MULTILINE)
    # Convert markdown italic *text* to <em>
    text = re.sub(r'(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)', r'<em>\1</em>', text)
    return text

app.jinja_env.filters['renderverdict'] = render_verdict


[redacted secret-like line]
    ip_raw = request.headers.get("X-Forwarded-For", request.remote_addr or "")
    return hashlib.sha256(ip_raw.encode()).hexdigest()[:16]


def score_country_with_minimax(country_name):
    """Score a country using MiniMax M2.7."""
    prompt = f"""You are the Countries CopeCheck Oracle — a forensic analyst of national AI/automation cope.

Score the country "{country_name}" on these dimensions (0-100 each):

1. PREPAREDNESS (0-100): Actual policy responses to AI displacement — retraining programs, UBI pilots, AI regulation, industrial strategy, education reform. Higher = MORE cope (less prepared, more denial).

2. LEADER COPE (0-100): What the head of state is publicly saying vs doing about AI/automation job displacement. The gap between rhetoric and reality. Higher = more cope.

3. EXPOSURE (0-100): How economically vulnerable the country is to AI automation. Services-heavy = more exposed. Higher = more exposed.

4. SCREWED SCORE (0-100): How objectively screwed this country is by AI/automation regardless of preparation. Factors: service sector GDP share, white-collar job percentage, BPO industry size, safety net strength (weaker = more screwed), income inequality. This is separate from cope — a country can be honest about AI (low cope) but still screwed. Higher = more screwed.

5. OVERALL COPE (0-100): Weighted average of preparedness, leader cope, and exposure. NOT including screwed score.

Also provide:
- A 1-2 sentence sardonic description of the country's AI stance
- The leader's name and title
- A brief policy assessment (2-3 sentences)
- Key economic sectors (comma-separated)
- Economy type (Services/Manufacturing/Mixed/Resource-based)

Return ONLY valid JSON:
{{
    "preparedness_score": number,
    "leader_cope_score": number,
    "exposure_score": number,
    "screwed_score": number,
    "overall_score": number,
    "description": "string",
    "leader_name": "string",
    "leader_title": "string",
    "policy_summary": "string",
    "key_sectors": "string",
    "economy_type": "string"
}}"""

    try:
        resp = http_requests.post(
            MINIMAX_URL,
            headers={
[redacted secret-like line]
                "Content-Type": "application/json"
            },
            json={
                "model": MINIMAX_MODEL,
                "messages": [{"role": "user", "content": prompt}],
                "temperature": 0.7,
[redacted secret-like line]
            },
            timeout=60
        )
        if resp.status_code != 200:
            return None, f"MiniMax API error: {resp.status_code}"

        data = resp.json()
        content = data['choices'][0]['message']['content']
        # Strip think tags from MiniMax reasoning
        content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL).strip()

        # Extract JSON from response
        import re
        json_match = re.search(r'\{[\s\S]*\}', content)
        if not json_match:
            return None, "No JSON in response"

        result = json.loads(json_match.group())
        return result, None

    except Exception as e:
        return None, str(e)


# ── CDN & Cache Headers ──────────────────────────────────────
@app.after_request
def add_cache_headers(response):
    """Set cache headers for Cloudflare CDN."""
    path = request.path
    if path.startswith('/static/'):
        # Static assets: cache aggressively at CDN and browser
        response.headers['Cache-Control'] = 'public, max-age=604800, stale-while-revalidate=86400'
    elif path.startswith('/api/'):
        # API responses: never cache
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
    elif path.endswith('.xml'):
        # Sitemaps/feeds: cache 1 hour
        response.headers['Cache-Control'] = 'public, max-age=3600'
    else:
        # HTML pages: short cache, but allow CDN to serve stale during spikes
        response.headers['Cache-Control'] = 'public, max-age=300, stale-while-revalidate=3600, stale-if-error=86400'
    # Vary by encoding so CDN caches gzip and plain separately
    response.headers.setdefault('Vary', 'Accept-Encoding')
    return response

@app.route('/')
def index():
    page = paginate_args()
    leaderboard, total = get_leaderboard_paginated(page, PER_PAGE)
    count = get_country_count()
    total_pages = max(1, (total + PER_PAGE - 1) // PER_PAGE)
    page = min(page, total_pages)
    return render_template('index.html', leaderboard=leaderboard, count=count,
                           page=page, total_pages=total_pages, total=total,
                           freshness=get_system_freshness())


@app.route('/country/<int:country_id>')
def country_detail(country_id):
    country = get_country(country_id)
    if not country:
        abort(404)
    return render_template('country.html', country=country,
                           freshness=get_system_freshness())


@app.route('/score')
def score_page():
    return render_template('score.html', scoring_enabled=COUNTRY_SCORING_ENABLED)


@app.route('/archive')
def archive_page():
    page = paginate_args()
    submissions, total = get_archive_paginated(page, PER_PAGE)
    count = get_archive_count()
    total_pages = max(1, (total + PER_PAGE - 1) // PER_PAGE)
    page = min(page, total_pages)
    return render_template('archive.html', submissions=submissions, count=count,
                           page=page, total_pages=total_pages)


@app.route('/api/score-country', methods=['POST'])
def api_score_country():
    if not COUNTRY_SCORING_ENABLED:
        return jsonify({
            "error": (
                "New country scoring is paused while the methodology is rebuilt "
                "around source-backed evidence. The published leaderboard is a "
                "dated historical model assessment."
            )
        }), 503
    data = request.get_json()
    if not data:
        return jsonify({"error": "No data provided"}), 400

    country_name = (data.get('country') or '').strip()
    captcha = (data.get('captcha') or '').strip().lower()

    if not country_name:
        return jsonify({"error": "Country name required"}), 400
    if len(country_name) > 100:
        return jsonify({"error": "Country name too long"}), 400
    if captcha not in CAPTCHA_ANSWERS:
        return jsonify({"error": "Wrong captcha answer"}), 400

    # Rate limit
[redacted secret-like line]
[redacted secret-like line]
    if not allowed:
        return jsonify({"error": f"Rate limited. Try again in {wait_mins} minutes."}), 429

    # Check if already scored
    existing = get_country_by_name(country_name)
    if existing:
        return jsonify({
            "already_exists": True,
            "country_id": existing['id'],
            "name": existing['name'],
            "overall_score": existing['overall_score'],
            "screwed_score": existing.get('screwed_score')
        })

    # Score with MiniMax
    result, error = score_country_with_minimax(country_name)
    if error:
        return jsonify({"error": f"Scoring failed: {error}"}), 500

    # Save to DB
[redacted secret-like line]
    country_data = {
        'name': country_name,
        'flag': data.get('flag', '🏳'),
        'leader_name': result.get('leader_name', 'Unknown'),
        'leader_title': result.get('leader_title', 'Leader'),
        'economy_type': result.get('economy_type', 'Mixed'),
        'key_sectors': result.get('key_sectors', ''),
        'description': result.get('description', ''),
        'preparedness_score': result.get('preparedness_score'),
        'leader_cope_score': result.get('leader_cope_score'),
        'exposure_score': result.get('exposure_score'),
        'overall_score': result.get('overall_score'),
        'screwed_score': result.get('screwed_score'),
        # The model is not allowed to manufacture quotation-like evidence.
        'leader_quotes': [],
        'policy_summary': result.get('policy_summary', ''),
        'submitted_by': 'user'
    }

    cid = upsert_country(country_data)

    return jsonify({
        "success": True,
        "country_id": cid,
        "name": country_name,
        "overall_score": result.get('overall_score'),
        "screwed_score": result.get('screwed_score'),
        "description": result.get('description', ''),
        "preparedness_score": result.get('preparedness_score'),
        "leader_cope_score": result.get('leader_cope_score'),
        "exposure_score": result.get('exposure_score')
    })


@app.route('/about')
def about():
    return render_template('about.html', freshness=get_system_freshness())


@app.errorhandler(404)
def not_found(e):
    return render_template('base.html', content='<p class="empty">404 — Country not found. Perhaps it already collapsed.</p>'), 404



@app.route("/sitemap.xml")
def sitemap():
    from flask import Response
    base = "https://countries.copecheck.com"
    pages = ["", "about", "score", "archive", "history"]
    countries = get_leaderboard()
    archive = get_archive()
    months = get_history_months()
    xml = '<?xml version="1.0" encoding="UTF-8"?>\n'
    xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
    for p in pages:
        xml += f'  <url><loc>{base}/{p}</loc><changefreq>weekly</changefreq></url>\n'
    for c in countries:
        xml += f'  <url><loc>{base}/country/{c["id"]}</loc><changefreq>monthly</changefreq></url>\n'
        xml += f'  <url><loc>{base}/country/{c["id"]}/history</loc><changefreq>monthly</changefreq></url>\n'
    for c in archive:
        xml += f'  <url><loc>{base}/country/{c["id"]}</loc><changefreq>monthly</changefreq></url>\n'
    for m in months:
        xml += f'  <url><loc>{base}/history/{m}</loc><changefreq>monthly</changefreq></url>\n'
    xml += '</urlset>'
    return Response(xml, mimetype="application/xml")

@app.route("/history")
def history_index():
    months = get_history_months()
    return render_template("history.html", months=months)


@app.route("/history/<month>")
def history_month(month):
    page = paginate_args()
    data, total = get_history_for_month_paginated(month, page, PER_PAGE)
    if not data and page == 1:
        abort(404)
    months = get_history_months()
    total_pages = max(1, (total + PER_PAGE - 1) // PER_PAGE)
    page = min(page, total_pages)
    return render_template("history_month.html", month=month, countries=data,
                           months=months, page=page, total_pages=total_pages)


@app.route("/country/<int:country_id>/history")
def country_history_page(country_id):
    country = get_country(country_id)
    if not country:
        abort(404)
    history = get_country_history(country["name"])
    return render_template("country_history.html", country=country, history=history)




# --- Newsletter subscribe proxy (beehiiv) ---
@app.route('/api/subscribe', methods=['POST'])
def api_newsletter_subscribe():
    """Proxy newsletter signups to beehiiv to avoid cross-origin blocks."""
    import requests as _req
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip()
    if not email or '@' not in email:
        return jsonify({'error': 'Invalid email'}), 400
    try:
        s = _req.Session()
        s.headers.update({'User-Agent': 'Mozilla/5.0'})
        page = s.get('https://copecheck.beehiiv.com', timeout=10)
        vt = ''
[redacted secret-like line]
        if m:
            vt = m.group(1)
        sf = ''
        m2 = re.search(r'name="signup_flow_id"\s+value="([^"]*)"', page.text)
        if m2:
            sf = m2.group(1)
        form = {
            'email': email,
[redacted secret-like line]
            'signup_flow_id': sf,
            'sent_from_orchid': 'true',
            'is_js_enabled': 'true',
            'fallback_path': '/',
        }
        r = s.post('https://copecheck.beehiiv.com/create', data=form, timeout=10, allow_redirects=True)
        if r.status_code < 400:
            return jsonify({'success': True, 'message': 'Subscribed!'})
        return jsonify({'error': 'Subscription failed', 'status': r.status_code}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500



# --- Feedback endpoint ---
@app.route('/api/feedback', methods=['POST'])
def api_feedback():
[redacted secret-like line]
    import json as _json, os as _os, threading
    from datetime import datetime as _dt
    data = request.get_json(silent=True) or {}
    text = data.get('text', '').strip()
    if not text or len(text) > 5000:
        return jsonify({'error': 'Invalid feedback'}), 400
    entry = {
        'text': text,
        'email': data.get('email', '').strip()[:200],
        'page': data.get('page', '')[:500],
        'site': 'countries.copecheck.com',
        'ts': _dt.utcnow().isoformat(),
        'ip': request.remote_addr,
    }
    # Save locally
    fb_dir = _os.path.join(_os.path.dirname(__file__), 'feedback')
    _os.makedirs(fb_dir, exist_ok=True)
    fb_file = _os.path.join(fb_dir, 'feedback.jsonl')
    with open(fb_file, 'a') as f:
        f.write(_json.dumps(entry) + "\n")
[redacted secret-like line]
    def _notify():
        try:
            import requests as _req
[redacted secret-like line]
        except Exception:
            pass
    threading.Thread(target=_notify, daemon=True).start()
    return jsonify({'success': True})



@app.route('/robots.txt')
def robots():
    return "User-agent: *\nAllow: /\n\nSitemap: https://countries.copecheck.com/sitemap.xml\n", 200, {'Content-Type': 'text/plain'}

@app.route('/ai-disclosure')
def ai_disclosure():
    return render_template('ai_disclosure.html')

if __name__ == "__main__":
    init_db()
    init_history()
    app.run(host="0.0.0.0", port=PORT, debug=False)
```
