---
type: "Source File"
title: "\"\"\""
description: "\"\"\" data.copecheck.com — AI Economic Data Dashboard Flask app aggregating real labour market data with Oracle commentary. \"\"\" from flask import Flask, render_template, request, jsonify, abort, Response import re from."
resource: "https://data.copecheck.com"
tags: ["copecheck", "data", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "data"
source_path: "copecheck-data/app.py"
---

# """

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

```py
"""
data.copecheck.com — AI Economic Data Dashboard
Flask app aggregating real labour market data with Oracle commentary.
"""
from flask import Flask, render_template, request, jsonify, abort, Response
import re
from markupsafe import Markup
from markdown_it import MarkdownIt
_md = MarkdownIt()
from datetime import datetime
import os
import sys
import json
import logging
from pathlib import Path

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

from db import (
    get_series_data, get_latest_by_country, get_commentary, get_all_commentary,
    get_series_list, get_countries_for_series, get_stats, get_series_freshness, init as init_db
)

from degrees_routes import degrees_bp, get_sitemap_urls as degrees_sitemap_urls
BASE = Path(__file__).parent
LOG_DIR = BASE / "logs"
LOG_DIR.mkdir(exist_ok=True)
logging.basicConfig(
    filename=str(LOG_DIR / "app.log"),
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger(__name__)

def create_app():
    app = Flask(__name__,
                template_folder=str(BASE / "templates"),
                static_folder=str(BASE / "static"))
[redacted secret-like line]


    try:
        init_db()
    except Exception as e:
        log.error(f"DB init failed: {e}")

    app.register_blueprint(degrees_bp)


    # ── Jinja filters for markdown rendering ──
    def md_to_html(text):
        if not text:
            return ""
        return Markup(_md.render(text))

    def strip_md(text):
        if not text:
            return ""
        text = re.sub(r"#{1,6}\s+", "", text)  # headers
        text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)  # bold
        text = re.sub(r"\*(.+?)\*", r"\1", text)  # italic
        text = re.sub(r"__(.+?)__", r"\1", text)  # bold alt
        text = re.sub(r"_(.+?)_", r"\1", text)  # italic alt
        return text

    app.jinja_env.filters["md"] = md_to_html
    app.jinja_env.filters["strip_md"] = strip_md
    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",
    }

    COUNTRY_FLAGS = {
        "US": "\U0001f1fa\U0001f1f8", "UK": "\U0001f1ec\U0001f1e7",
        "DE": "\U0001f1e9\U0001f1ea", "FR": "\U0001f1eb\U0001f1f7",
        "ES": "\U0001f1ea\U0001f1f8", "IT": "\U0001f1ee\U0001f1f9",
        "NL": "\U0001f1f3\U0001f1f1", "SE": "\U0001f1f8\U0001f1ea",
        "PL": "\U0001f1f5\U0001f1f1", "EU": "\U0001f1ea\U0001f1fa",
    }

    SERIES_CONFIG = {
        "youth_unemployment": {"name": "Youth Unemployment (15-24)", "color": "#e63946", "unit": "%"},
        "labour_share_gdp": {"name": "Labour Share of GDP", "color": "#2a9d8f", "unit": "%"},
        "gdp_growth": {"name": "GDP Growth Rate", "color": "#4ade80", "unit": "%"},
        "employment_ratio": {"name": "Employment Ratio", "color": "#3b82f6", "unit": "%"},
        "labour_force_participation": {"name": "Labour Force Participation", "color": "#f4a261", "unit": "%"},
        "neet_rate": {"name": "NEET Rate (Youth)", "color": "#9b59b6", "unit": "%"},
        "gini_index": {"name": "Gini Index", "color": "#e76f51", "unit": ""},
        "industry_employment_share": {"name": "Industry Employment Share", "color": "#06b6d4", "unit": "%"},
        "services_employment_share": {"name": "Services Employment Share", "color": "#fbbf24", "unit": "%"},
        "ai_diffusion": {"name": "AI Diffusion (15-64 population)", "color": "#8b5cf6", "unit": "%"},
    }

    COPE_TYPE_NAMES = {
        "pure-cope": "Pure Cope", "heavy-cope": "Heavy Cope",
        "partial-cope": "Partial Cope", "somewhat-lucid": "Somewhat Lucid",
        "reality": "Actually Addresses Reality",
    }

    def get_context():
        try:
            stats = get_stats()
        except:
            stats = {"total_series": 0, "total_data_points": 0, "total_commentary": 0, "countries": 0}
        try:
            freshness = get_series_freshness()
        except:
            freshness = {}
        return {
            "country_names": COUNTRY_NAMES, "country_flags": COUNTRY_FLAGS,
            "series_config": SERIES_CONFIG, "cope_type_names": COPE_TYPE_NAMES,
            "stats": stats, "freshness": freshness,
        }


    # ── CDN & Cache Headers ──────────────────────────────────────
    @app.after_request
    def add_cache_headers(response):
        path = request.path
        if path.startswith('/static/'):
            response.headers['Cache-Control'] = 'public, max-age=604800, stale-while-revalidate=86400'
        elif path.startswith('/api/'):
            response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
        elif path.endswith('.xml'):
            response.headers['Cache-Control'] = 'public, max-age=3600'
        else:
            response.headers['Cache-Control'] = 'public, max-age=300, stale-while-revalidate=3600, stale-if-error=86400'
        response.headers.setdefault('Vary', 'Accept-Encoding')
        return response

    @app.route("/")
    def index():
        ctx = get_context()
        try:
            ctx["latest_comments"] = get_all_commentary(limit=6)
            ctx["last_updated"] = datetime.now().strftime("%Y-%m-%d")
        except Exception as e:
            log.error(f"Dashboard error: {e}")
            ctx["latest_comments"] = []
        return render_template("index.html", **ctx)

    @app.route("/youth")
    def youth():
        ctx = get_context()
        try:
            ctx["comments"] = get_commentary(series_id="youth_unemployment", limit=10)
        except Exception as e:
            log.error(f"Youth page error: {e}")
            ctx["comments"] = []
        return render_template("youth.html", **ctx)

    @app.route("/labour-share")
    def labour_share():
        ctx = get_context()
        try:
            ctx["comments"] = get_commentary(series_id="labour_share_gdp", limit=10)
        except Exception as e:
            log.error(f"Labour share error: {e}")
            ctx["comments"] = []
        return render_template("labour_share.html", **ctx)

    @app.route("/country/<code>")
    def country(code):
        ctx = get_context()
        uc = code.upper()
        if uc not in COUNTRY_NAMES:
            abort(404)
        ctx["country_code"] = uc
        ctx["country_name"] = COUNTRY_NAMES[uc]
        ctx["country_flag"] = COUNTRY_FLAGS.get(uc, "")
        return render_template("country.html", **ctx)

    @app.route("/feed")
    def feed():
        ctx = get_context()
        page = request.args.get("page", 1, type=int)
        series_filter = request.args.get("series", "all")
        verdict_filter = request.args.get("verdict", "all")
        try:
            per_page = 12
            offset = (page - 1) * per_page
            all_comments = get_all_commentary(limit=500)
            if series_filter != "all":
                all_comments = [c for c in all_comments if c.get("series_id") == series_filter]
            if verdict_filter != "all":
                all_comments = [c for c in all_comments if c.get("cope_type") == verdict_filter]
            total = len(all_comments)
            ctx["comments"] = all_comments[offset:offset + per_page]
            ctx["page"] = page
            ctx["total_pages"] = max(1, (total + per_page - 1) // per_page)
            ctx["series_filter"] = series_filter
            ctx["verdict_filter"] = verdict_filter
        except Exception as e:
            log.error(f"Feed error: {e}")
            ctx.update({"comments": [], "page": 1, "total_pages": 1,
                        "series_filter": "all", "verdict_filter": "all"})
        return render_template("feed.html", **ctx)

    @app.route("/about")
    def about():
        return render_template("about.html", **get_context())

    @app.route("/report/<slug>")
    def report(slug):
        from db import get_commentary_by_slug
        ctx = get_context()
        r = get_commentary_by_slug(slug)
        if not r:
            abort(404)
        if r.get("key_quotes"):
            try:
                r["key_quotes_list"] = json.loads(r["key_quotes"])
            except Exception:
                r["key_quotes_list"] = []
        else:
            r["key_quotes_list"] = []
        ctx["r"] = r
        return render_template("report.html", **ctx)

    @app.route("/api/series/<series_id>")
    def api_series(series_id):
        try:
            data = get_latest_by_country(series_id)
            if not data:
                return jsonify({"error": "No data"}), 404
            return jsonify({"series_id": series_id, "data_points": data, "count": len(data)})
        except Exception as e:
            log.error(f"API series error: {e}")
            return jsonify({"error": "Server error"}), 500

    @app.route("/api/countries/<series_id>")
    def api_countries(series_id):
        country_code = request.args.get("country")
        try:
            if country_code:
                data = get_series_data(series_id, country=country_code.upper())
            else:
                data = get_latest_by_country(series_id)
            if not data:
                return jsonify({"error": "No data"}), 404
            return jsonify({"series_id": series_id, "country": country_code, "data": data, "count": len(data)})
        except Exception as e:
            log.error(f"API countries error: {e}")
            return jsonify({"error": "Server error"}), 500

    @app.route("/sitemap.xml")
    def sitemap():
        base = "https://data.copecheck.com"
        pages = [
            {"loc": f"{base}/", "priority": "1.0"},
            {"loc": f"{base}/youth", "priority": "0.9"},
            {"loc": f"{base}/labour-share", "priority": "0.9"},
            {"loc": f"{base}/feed", "priority": "0.8"},
            {"loc": f"{base}/about", "priority": "0.5"},
        ]
        for code in COUNTRY_NAMES:
            pages.append({"loc": f"{base}/country/{code.lower()}", "priority": "0.7"})
        try:
            from db import get_report_slugs as _report_slugs
            for _rep in _report_slugs():
                pages.append({"loc": f"{base}/report/{_rep['slug']}", "priority": "0.8"})
        except Exception as _e:
            log.error(f"sitemap reports: {_e}")
        xml = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
        for p in pages:
            xml += f'  <url><loc>{p["loc"]}</loc><priority>{p["priority"]}</priority></url>\n'
        for deg_url in degrees_sitemap_urls():
            xml += f'  <url><loc>{base}{deg_url}</loc><priority>0.7</priority></url>\n'
        xml += "</urlset>"
        return Response(xml, mimetype="application/xml")

    @app.route("/robots.txt")
    def robots():
        return Response("User-agent: *\nAllow: /\nSitemap: https://data.copecheck.com/sitemap.xml\n",
                        mimetype="text/plain")

    @app.route("/ai-disclosure")
    def ai_disclosure():
        return render_template("ai_disclosure.html", **get_context())

    @app.errorhandler(404)
    def not_found(e):
        return render_template("404.html", **get_context()), 404

    @app.errorhandler(500)
    def server_error(e):
        return render_template("500.html", **get_context()), 500

    return app

app = create_app()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8104, 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
```
