---
type: "Source File"
title: "\"\"\"EU CopeCheck — Flask application.\"\"\""
description: "\"\"\"EU CopeCheck — Flask application.\"\"\" import os import json import hashlib import logging import time import re from datetime import datetime from functools import lru_cache from flask import Flask, render_template."
resource: "https://eu.copecheck.com"
tags: ["copecheck", "eu", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "eu"
source_path: "copecheck-eu/app.py"
---

# """EU CopeCheck — Flask application."""

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

```py
"""EU CopeCheck — Flask application."""
import os
import json
import hashlib
import logging
import time
import re
from datetime import datetime
from functools import lru_cache

from flask import Flask, render_template, request, jsonify, abort, redirect, url_for
from markupsafe import Markup
import markdown

import db

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("eu_app")

app = Flask(__name__)


[redacted secret-like line]


db.init_db()

# ── Slug helpers ──

def _slugify(text):
    """Convert text to URL-friendly slug."""
    s = str(text).lower().strip()
    s = re.sub(r'[àáâãäå]', 'a', s)
    s = re.sub(r'[èéêë]', 'e', s)
    s = re.sub(r'[ìíîï]', 'i', s)
    s = re.sub(r'[òóôõö]', 'o', s)
    s = re.sub(r'[ùúûü]', 'u', s)
    s = re.sub(r'[ñ]', 'n', s)
    s = re.sub(r'[ç]', 'c', s)
    s = re.sub(r'[^a-z0-9\s-]', '', s)
    s = re.sub(r'[\s_]+', '-', s)
    s = re.sub(r'-+', '-', s)
    return s.strip('-')

# Build slug lookup caches (refreshed on restart)
def _build_country_slugs():
    countries = db.get_all_countries(order_by="id ASC")
    slug_to_id = {}
    id_to_slug = {}
    for c in countries:
        slug = _slugify(c['name'])
        slug_to_id[slug] = c['id']
        id_to_slug[c['id']] = slug
    return slug_to_id, id_to_slug

def _build_law_slugs():
    laws = db.get_all_laws(order_by="id ASC")
    slug_to_id = {}
    id_to_slug = {}
    for l in laws:
        slug = _slugify(l['title'])
        slug_to_id[slug] = l['id']
        id_to_slug[l['id']] = slug
    return slug_to_id, id_to_slug

def _build_institution_slugs():
    insts = db.get_all_institutions()
    slug_to_id = {}
    id_to_slug = {}
    for i in insts:
        slug = _slugify(i['name'])
        slug_to_id[slug] = i['id']
        id_to_slug[i['id']] = slug
    return slug_to_id, id_to_slug

COUNTRY_SLUG_TO_ID, COUNTRY_ID_TO_SLUG = _build_country_slugs()
LAW_SLUG_TO_ID, LAW_ID_TO_SLUG = _build_law_slugs()
INST_SLUG_TO_ID, INST_ID_TO_SLUG = _build_institution_slugs()

# ── Rate limiting for oracle ──
_rate_limits = {}


[redacted secret-like line]
    ip = request.headers.get('X-Forwarded-For', request.remote_addr or '').split(',')[0].strip()
    return hashlib.sha256(ip.encode()).hexdigest()[:16]


[redacted secret-like line]
    now = time.time()
[redacted secret-like line]
    history = _rate_limits.get(key, [])
    history = [t for t in history if now - t < window]
    if len(history) >= max_req:
        wait = int((history[0] + window - now) / 60) + 1
        return False, wait
    return True, 0


[redacted secret-like line]
[redacted secret-like line]
    _rate_limits.setdefault(key, []).append(time.time())


# ── Template filters ──

@app.template_filter('slugify')
def slugify_filter(text):
    return _slugify(text)


@app.template_filter('copecolor')
def copecolor(score):
    try:
        s = float(score or 0)
    except (ValueError, TypeError):
        return 'cope-moderate'
    if s >= 80: return 'cope-terminal'
    if s >= 60: return 'cope-heavy'
    if s >= 40: return 'cope-moderate'
    if s >= 20: return 'cope-partial'
    return 'cope-lucid'


@app.template_filter('copelabel')
def copelabel(score):
    try:
        s = float(score or 0)
    except (ValueError, TypeError):
        return 'Moderate'
    if s >= 80: return 'Terminal Copium'
    if s >= 60: return 'Heavy Cope'
    if s >= 40: return 'Moderate Cope'
    if s >= 20: return 'Partial Cope'
    return 'Lucid'


@app.template_filter('screwedcolor')
def screwedcolor(score):
    try:
        s = float(score or 0)
    except (ValueError, TypeError):
        return 'screwed-moderate'
    if s >= 80: return 'screwed-critical'
    if s >= 60: return 'screwed-high'
    if s >= 40: return 'screwed-moderate'
    return 'screwed-low'


@app.template_filter('screwedlabel')
def screwedlabel(score):
    try:
        s = float(score or 0)
    except (ValueError, TypeError):
        return 'Moderate'
    if s >= 80: return 'Critically Screwed'
    if s >= 60: return 'Quite Screwed'
    if s >= 40: return 'Moderately Screwed'
    if s >= 20: return 'Somewhat Screwed'
    return 'Not Yet Screwed'


@app.template_filter('render_md')
def render_md(text):
    if not text:
        return ''
    return Markup(markdown.markdown(str(text), extensions=['tables']))


@app.template_filter('parse_quotes')
def parse_quotes(text):
    if not text:
        return []
    try:
        return json.loads(text)
    except (json.JSONDecodeError, TypeError):
        return []


@app.template_filter('fmtdate')
def fmtdate(text):
    if not text:
        return ''
    try:
        dt = datetime.fromisoformat(str(text).replace('Z', '+00:00'))
        return dt.strftime('%d %b %Y')
    except Exception:
        return str(text)[:10]


@app.template_filter('nl2br')
def nl2br(text):
    if not text:
        return ''
    return Markup(str(text).replace('\n', '<br>\n'))


# ── ROUTES ──

# ── 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():
    countries = db.get_all_countries()
    return render_template('index.html', countries=countries, country_slugs=COUNTRY_ID_TO_SLUG)


@app.route('/country/<slug>')
def country_detail(slug):
    # Try slug lookup first, then fallback to numeric ID
    if slug in COUNTRY_SLUG_TO_ID:
        country_id = COUNTRY_SLUG_TO_ID[slug]
    elif slug.isdigit():
        country_id = int(slug)
        # 301 redirect old numeric URLs to new slug URLs
        if country_id in COUNTRY_ID_TO_SLUG:
            return redirect(f'/country/{COUNTRY_ID_TO_SLUG[country_id]}', code=301)
    else:
        abort(404)
    country = db.get_country(country_id)
    if not country:
        abort(404)
    stats = db.get_cached_stats(country['code'])
    econ_data = db.get_latest_economic_data(country['code'])
    last_fetch = db.get_meta("last_eurostat_fetch") or "Never"
    country_slug = COUNTRY_ID_TO_SLUG.get(country_id, slug)
    return render_template('country.html', country=country, stats=stats,
                           econ_data=econ_data, last_fetch=last_fetch,
                           country_slug=country_slug)


@app.route('/laws')
def laws_list():
    page = request.args.get('page', 1, type=int)
    per_page = 20
    all_laws = db.get_all_laws()
    total_pages = max(1, (len(all_laws) + per_page - 1) // per_page)
    page = max(1, min(page, total_pages))
    start = (page - 1) * per_page
    laws = all_laws[start:start + per_page]
    return render_template('laws.html', laws=laws, page=page, total_pages=total_pages)


@app.route('/law/<slug>')
def law_detail(slug):
    if slug in LAW_SLUG_TO_ID:
        law_id = LAW_SLUG_TO_ID[slug]
    elif slug.isdigit():
        law_id = int(slug)
        if law_id in LAW_ID_TO_SLUG:
            return redirect(f'/law/{LAW_ID_TO_SLUG[law_id]}', code=301)
    else:
        abort(404)
    law = db.get_law(law_id)
    if not law:
        abort(404)
    law_slug = LAW_ID_TO_SLUG.get(law_id, slug)
    return render_template('law.html', law=law, law_slug=law_slug)


@app.route('/institutions')
def institutions_list():
    institutions = db.get_all_institutions()
    return render_template('institutions.html', institutions=institutions)


@app.route('/institution/<slug>')
def institution_detail(slug):
    if slug in INST_SLUG_TO_ID:
        inst_id = INST_SLUG_TO_ID[slug]
    elif slug.isdigit():
        inst_id = int(slug)
        if inst_id in INST_ID_TO_SLUG:
            return redirect(f'/institution/{INST_ID_TO_SLUG[inst_id]}', code=301)
    else:
        abort(404)
    inst = db.get_institution(inst_id)
    if not inst:
        abort(404)
    inst_slug = INST_ID_TO_SLUG.get(inst_id, slug)
    return render_template('institution.html', institution=inst, inst_slug=inst_slug)


@app.route('/data')
def data_page():
    countries = db.get_all_countries()
    return render_template('data.html', countries=countries)


@app.route('/ask-oracle')
def ask_oracle_page():
    recent = db.get_recent_questions(limit=10)
    return render_template('ask_oracle.html', recent=recent)


@app.route('/api/ask-oracle', methods=['POST'])
def api_ask_oracle():
[redacted secret-like line]
[redacted secret-like line]
    if not allowed:
        return jsonify({"error": f"Rate limited. Try again in {wait} minutes."}), 429

    data = request.get_json()
    question = (data.get('question') or '').strip()
    if not question:
        return jsonify({"error": "No question provided"}), 400
    if len(question) > 2000:
        return jsonify({"error": "Question too long"}), 400

    # Build context from countries + laws
    countries = db.get_all_countries()
    laws = db.get_all_laws()
    context_parts = ["EU MEMBER STATES:"]
    for c in countries[:10]:  # Top 10 by cope
        context_parts.append(f"- {c['name']}: cope {c['overall_score']:.0f}, screwed {c['screwed_score']:.0f}, demographic {c['demographic_score']:.0f}")
    context_parts.append("\nKEY EU LAWS:")
    for l in laws[:5]:
        context_parts.append(f"- {l['title']}: cope {l['overall_cope_score']:.0f}")
    data_context = "\n".join(context_parts)

    import scorer
    answer, model = scorer.ask_oracle(question, data_context)
    if answer:
[redacted secret-like line]
[redacted secret-like line]
        return jsonify({"answer": answer, "model": model, "question_id": qid})
    return jsonify({"error": "The Oracle is unavailable. Try again shortly."}), 503


@app.route('/question/<int:qid>')
def question_detail(qid):
    q = db.get_question(qid)
    if not q:
        abort(404)
    return render_template('question.html', question=q)


@app.route('/feed')
def feed():
    page = request.args.get('page', 1, type=int)
    per_page = 20
    all_articles = db.get_recent_articles(limit=200)
    total_pages = max(1, (len(all_articles) + per_page - 1) // per_page)
    page = max(1, min(page, total_pages))
    start = (page - 1) * per_page
    articles = all_articles[start:start + per_page]
    return render_template('feed.html', articles=articles, page=page, total_pages=total_pages)




@app.route('/article/<slug>')
def article_detail(slug):
    # Build slug -> id map from all articles
    all_articles = db.get_recent_articles(limit=5000)
    article = None
    # Try slug match first
    for a in all_articles:
        if _slugify(a['title']) == slug:
            article = a
            break
    # Fallback: numeric id
    if article is None and slug.isdigit():
        article = db.get_article_by_id(int(slug))
    if article is None:
        abort(404)
    return render_template('article_detail.html', article=article, slug=slug)

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


@app.route('/history/<month>')
def history_month(month):
    months = db.get_history_months()
    countries = db.get_history_for_month(month)
    return render_template('history_month.html', month=month, months=months, countries=countries)


@app.route('/about')
def about():
    return render_template('about.html')


# ── Sitemap ──

@app.route('/economics')
def economics_page():
    """Live economic data dashboard for all EU countries."""
    countries = db.get_all_countries()
    all_indicators = db.get_all_latest_indicators()
    last_fetch = db.get_meta("last_eurostat_fetch") or "Never"
    return render_template('economics.html',
                           countries=countries,
                           indicators=all_indicators,
                           country_slugs=COUNTRY_ID_TO_SLUG,
                           last_fetch=last_fetch)


@app.route('/api/chart-data/<country_code>/<indicator>')
def api_chart_data(country_code, indicator):
    """Return time-series data for Chart.js."""
    allowed_indicators = [
        "unemployment_rate", "youth_unemployment_rate", "gdp_meur",
        "gdp_growth_pct", "gdp_per_capita_eur", "old_age_dependency_ratio",
        "inflation_hicp_pct", "services_pct_gdp"
    ]
    if indicator not in allowed_indicators:
        return jsonify({"error": "Invalid indicator"}), 400
    data = db.get_economic_data_for_chart(country_code.upper(), indicator)
    return jsonify(data)



@app.route('/sitemap.xml')
def sitemap():
    from flask import Response
    pages = ['/', '/laws', '/institutions', '/data', '/economics', '/ask-oracle', '/feed', '/about', '/history']
    countries = db.get_all_countries()
    laws = db.get_all_laws()
    xml = ['<?xml version="1.0" encoding="UTF-8"?>',
           '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
    for p in pages:
        xml.append(f'<url><loc>https://eu.copecheck.com{p}</loc><changefreq>weekly</changefreq></url>')
    for c in countries:
        slug = COUNTRY_ID_TO_SLUG.get(c['id'], str(c['id']))
        xml.append(f'<url><loc>https://eu.copecheck.com/country/{slug}</loc><changefreq>monthly</changefreq><priority>0.8</priority></url>')
    for l in laws:
        slug = LAW_ID_TO_SLUG.get(l['id'], str(l['id']))
        xml.append(f'<url><loc>https://eu.copecheck.com/law/{slug}</loc><changefreq>monthly</changefreq><priority>0.7</priority></url>')
    institutions = db.get_all_institutions()
    for i in institutions:
        slug = INST_ID_TO_SLUG.get(i['id'], str(i['id']))
        xml.append(f'<url><loc>https://eu.copecheck.com/institution/{slug}</loc><changefreq>monthly</changefreq><priority>0.6</priority></url>')
    xml.append('</urlset>')
    return Response('\n'.join(xml), mimetype='application/xml')


# ── robots.txt + llms.txt ──

@app.route('/robots.txt')
def robots():
    from flask import Response
    txt = """User-agent: *
Allow: /
Sitemap: https://eu.copecheck.com/sitemap.xml

User-agent: GPTBot
Allow: /

User-agent: ChatGPT-User
Allow: /

User-agent: Claude-Web
Allow: /

User-agent: Anthropic-AI
Allow: /

User-agent: Google-Extended
Allow: /
"""
    return Response(txt.strip(), mimetype='text/plain')


@app.route('/llms.txt')
def llms_txt():
    from flask import Response
    txt = """# EU CopeCheck — eu.copecheck.com

> Scoring 27 EU member states and 12 EU laws on AI displacement cope using the Discontinuity Thesis framework.

## What this site does
EU CopeCheck scores EU countries on how much their governments are coping (denying, deflecting, minimising) about AI's impact on jobs, demographics, and structural economics. Each country gets scores for Preparedness, Leader Cope, Exposure, and Demographic Doom. Laws are scored through three philosophical lenses: Unit Cost Dominance, Prisoner's Dilemma, and Sorites Paradox.

## Key pages
- /country/{name} — Individual country cope analysis (e.g. /country/greece, /country/germany)
- /law/{name} — Individual EU law cope analysis through three lenses
- /institution/{name} — EU institution cope scoring
- /laws — All scored EU laws
- /institutions — All scored EU institutions
- /data — Sortable data table of all 27 member states
- /ask-oracle — Ask the EU Oracle of Obsolescence
- /feed — Latest scored articles
- /sitemap.xml — Full sitemap

## Scoring methodology
Countries: preparedness (25%) + leader_cope (20%) + exposure (25%) + demographics (30%)
Laws: unit_cost_dominance (40%) + prisoners_dilemma (30%) + sorites_paradox (30%)
Scale: 0-100 where 100 = maximum cope

## Part of the CopeCheck Network
- https://copecheck.com — Main site (global figures)
- https://uk.copecheck.com — UK-specific
- https://countries.copecheck.com — Country-by-country
- https://eu.copecheck.com — EU member states and laws (this site)
"""
    return Response(txt.strip(), mimetype='text/plain')


@app.route('/llms-full.txt')
def llms_full():
    from flask import Response
    countries = db.get_all_countries()
    laws = db.get_all_laws()
    institutions = db.get_all_institutions()
    parts = ["# EU CopeCheck — Full Data Export for LLMs\n"]
    parts.append("## Country Leaderboard (ranked by screwed score)\n")
    sorted_countries = sorted(countries, key=lambda c: c.get('screwed_score', 0) or 0, reverse=True)
    for i, c in enumerate(sorted_countries, 1):
        parts.append(f"{i}. {c['name']} — Cope: {c.get('overall_score', 0):.0f}, Screwed: {c.get('screwed_score', 0):.0f}, Demographic: {c.get('demographic_score', 0):.0f}")
        if c.get('description'):
            parts.append(f"   {c['description'][:200]}")
    parts.append("\n## EU Laws (ranked by cope score)\n")
    for l in laws:
        parts.append(f"- {l['title']} — Cope: {l.get('overall_cope_score', 0):.0f} (Unit Cost: {l.get('unit_cost_score', 0):.0f}, Prisoner: {l.get('prisoner_dilemma_score', 0):.0f}, Sorites: {l.get('sorites_score', 0):.0f})")
    parts.append("\n## EU Institutions\n")
    for inst in institutions:
        parts.append(f"- {inst['name']} — Cope: {inst.get('cope_score', 0):.0f}")
    return Response("\n".join(parts), mimetype='text/plain')


# ── Error handlers ──

@app.errorhandler(404)
def not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def server_error(e):
    return render_template('500.html'), 500





def _add_to_resend(email, first_name=""):
    """Add subscriber to Resend Cope Report audience."""
    import requests as _resend_req, os as _os
[redacted secret-like line]
    audience_id = "e0c71613-ce4e-4e25-a920-515dfe0a90ff"
[redacted secret-like line]
        return
    try:
        _resend_req.post(
            f"https://api.resend.com/audiences/{audience_id}/contacts",
[redacted secret-like line]
            json={"email": email, "first_name": first_name, "unsubscribed": False},
            timeout=5
        )
    except Exception:
        pass  # Don't fail the main subscription if Resend is down

# --- Newsletter subscribe (Resend) ---
@app.route('/api/subscribe', methods=['POST'])
def api_newsletter_subscribe():
    """Subscribe email to Resend Cope Report audience."""
    import requests as _req, os as _os
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip()
    if not email or '@' not in email:
        return jsonify({'success': False, 'message': 'Please enter a valid email address.'}), 400
[redacted secret-like line]
[redacted secret-like line]
        return jsonify({'success': False, 'message': 'Server configuration error.'}), 500
    try:
        r = _req.post(
            'https://api.resend.com/audiences/e0c71613-ce4e-4e25-a920-515dfe0a90ff/contacts',
[redacted secret-like line]
            json={'email': email, 'unsubscribed': False},
            timeout=8
        )
        if r.status_code in (200, 201):
            return jsonify({'success': True, 'message': "You're subscribed!"})
        if r.status_code == 422:
            return jsonify({'success': True, 'message': "Already subscribed — you're good!"})
        return jsonify({'success': False, 'message': 'Something went wrong. Please try again.'}), 500
    except Exception:
        return jsonify({'success': False, 'message': 'Connection error. Please try again.'}), 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': 'eu.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('/ai-disclosure')
def ai_disclosure():
    return render_template('ai_disclosure.html')

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 8100))
    app.run(host='0.0.0.0', port=port, debug=True)


# ── Trailing-slash canonicalisation (added 2026-09-26, infra audit) ──
# Flask 404s on "/foo/" when the route is declared as "/foo". This installs a
# before_request hook that 301s the slashed form to the canonical slash-less
# one, but only when the slashed form is not itself a real route. Revert by
# deleting these three lines and slash_canonical.py.
from slash_canonical import install_slash_canonicaliser  # noqa: E402
install_slash_canonicaliser(app)  # noqa: E402
```
