---
type: "Source File"
title: "import re"
description: "import re import json import os from datetime import datetime from flask import Flask, render_template, abort, request, Response, url_for, jsonify app = Flask(__name__) # --- CopeCheck heuristic sector-exposure weights."
resource: "https://cities.copecheck.com"
tags: ["copecheck", "cities", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "cities"
source_path: "copecheck-cities/app.py"
---

# import re

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

```py
import re
import json
import os
from datetime import datetime
from flask import Flask, render_template, abort, request, Response, url_for, jsonify

app = Flask(__name__)



# --- CopeCheck heuristic sector-exposure weights ---
#
# Frey & Osborne estimated occupation-level susceptibility, not probabilities
# for whole SIC/NAICS sectors.  These hand-set sector weights are therefore a
# comparative CopeCheck heuristic and must not be described as official risk
# probabilities.
SECTOR_WEIGHTS = {
    "administrative_support": 0.85,
    "retail": 0.80,
    "manufacturing": 0.82,
    "financial_services": 0.75,
    "transport_storage": 0.78,
    "wholesale": 0.55,
    "information_communication": 0.50,
    "accommodation_food": 0.48,
    "health": 0.18,
    "education": 0.15,
    "construction": 0.28,
    "agriculture": 0.25,
    "public_admin": 0.22,
    "arts_recreation": 0.20,
    "professional_scientific": 0.30,
    "real_estate": 0.40,
}

SECTOR_LABELS = {
    "agriculture": "Agriculture, Forestry & Fishing",
    "manufacturing": "Manufacturing",
    "construction": "Construction",
    "wholesale": "Wholesale",
    "retail": "Retail",
    "transport_storage": "Transport & Storage",
    "accommodation_food": "Accommodation & Food Services",
    "information_communication": "Information & Communication",
    "financial_services": "Financial & Insurance Services",
    "real_estate": "Real Estate",
    "professional_scientific": "Professional, Scientific & Technical",
    "administrative_support": "Administrative & Support Services",
    "public_admin": "Public Administration & Defence",
    "education": "Education",
    "health": "Human Health & Social Work",
    "arts_recreation": "Arts, Entertainment & Recreation",
}

SECTOR_RISK_TIER = {
    "administrative_support": "high",
    "retail": "high",
    "manufacturing": "high",
    "financial_services": "high",
    "transport_storage": "high",
    "wholesale": "medium",
    "information_communication": "medium",
    "accommodation_food": "medium",
    "health": "low",
    "education": "low",
    "construction": "low",
    "agriculture": "low",
    "public_admin": "low",
    "arts_recreation": "low",
    "professional_scientific": "low",
    "real_estate": "medium",
}

COUNTRIES = {
    "uk": {
        "name": "United Kingdom",
        "flag": "\U0001f1ec\U0001f1e7",
        "data_file": "uk.json",
        "description": "51 cities compared using a bundled historical workforce-composition snapshot and CopeCheck heuristic sector-exposure weights.",
    },
    "us": {
        "name": "United States",
        "flag": "\U0001f1fa\U0001f1f8",
        "data_file": "us.json",
        "description": "50 cities — one per state — compared using a bundled historical workforce-composition snapshot and CopeCheck heuristic sector-exposure weights.",
    },
    "ie": {
        "name": "Ireland",
        "flag": "\U0001f1ee\U0001f1ea",
        "data_file": "ie.json",
        "description": "15 cities compared using a bundled historical workforce-composition snapshot labelled to CSO Census 2022 and CopeCheck heuristic sector-exposure weights.",
    },
    "ca": {
        "name": "Canada",
        "flag": "\U0001f1e8\U0001f1e6",
        "data_file": "ca.json",
        "description": "15 cities compared using a bundled historical workforce-composition snapshot and CopeCheck heuristic sector-exposure weights.",
    },
    "au": {
        "name": "Australia",
        "flag": "\U0001f1e6\U0001f1fa",
        "data_file": "au.json",
        "description": "15 cities compared using a bundled historical workforce-composition snapshot labelled to the ABS 2021 Census and CopeCheck heuristic sector-exposure weights.",
    },
    "nz": {
        "name": "New Zealand",
        "flag": "\U0001f1f3\U0001f1ff",
        "data_file": "nz.json",
        "description": "13 cities compared using a bundled historical workforce-composition snapshot and CopeCheck heuristic sector-exposure weights.",
    },
}


def city_dataset_status():
    data_dir = os.path.join(os.path.dirname(__file__), "data")
    dates = []
    for info in COUNTRIES.values():
        path = os.path.join(data_dir, info["data_file"])
        if os.path.exists(path):
            dates.append(datetime.fromtimestamp(os.path.getmtime(path)).date().isoformat())
    return {
        "first_import": min(dates) if dates else "unknown",
        "last_import": max(dates) if dates else "unknown",
        "current_year": datetime.now().year,
    }


@app.context_processor
def inject_city_dataset_status():
    return {"city_dataset_status": city_dataset_status()}


# --- Live UK labour market context [redacted]
#
# data/uk_labour.json is produced by labour_fetcher.py from the ONS time series
# API, the ONS regional labour market bulletin, and NOMIS.  It is deliberately
# kept separate from the workforce-composition snapshot in data/uk.json: the
# exposure score is structural and is NOT recalculated from these figures.
# Nothing here feeds compute_score().

_LABOUR_CACHE = {"mtime": None, "payload": None}


def load_uk_labour():
    path = os.path.join(os.path.dirname(__file__), "data", "uk_labour.json")
    try:
        mtime = os.path.getmtime(path)
    except OSError:
        return None
    if _LABOUR_CACHE["mtime"] == mtime:
        return _LABOUR_CACHE["payload"]
    try:
        with open(path, "r") as f:
            payload = json.load(f)
    except (OSError, ValueError):
        app.logger.warning("uk_labour.json present but unreadable")
        return None
    _LABOUR_CACHE["mtime"] = mtime
    _LABOUR_CACHE["payload"] = payload
    return payload


_RTI_CACHE = {"mtime": None, "payload": None}


def load_uk_rti():
    """HMRC PAYE RTI payrolled employees, parsed from the ONS reference table.

    Optional: if rti_fetcher.py has never run or its last run failed loudly,
    this returns None and callers fall back to the pinned figures carried in
    uk_labour.json, so a bad parse can never put a wrong number on the page.
    """
    path = os.path.join(os.path.dirname(__file__), "data", "uk_rti.json")
    try:
        mtime = os.path.getmtime(path)
    except OSError:
        return None
    if _RTI_CACHE["mtime"] == mtime:
        return _RTI_CACHE["payload"]
    try:
        with open(path, "r") as f:
            payload = json.load(f)
    except (OSError, ValueError):
        app.logger.warning("uk_rti.json present but unreadable")
        return None
    _RTI_CACHE["mtime"] = mtime
    _RTI_CACHE["payload"] = payload
    return payload


_LAYOFFS_CACHE = {"mtime": None, "payload": None}


def load_uk_layoffs():
    """Local snapshot of UK layoffs, written by layoffs_sync.py.

    This reads only this site's own file. copecheck-layoffs is never contacted
    at request time, so an outage there cannot affect a city page: the worst
    case is a stale snapshot, and a missing file simply omits the block.
    """
    path = os.path.join(os.path.dirname(__file__), "data", "uk_layoffs.json")
    try:
        mtime = os.path.getmtime(path)
    except OSError:
        return None
    if _LAYOFFS_CACHE["mtime"] == mtime:
        return _LAYOFFS_CACHE["payload"]
    try:
        with open(path, "r") as f:
            payload = json.load(f)
    except (OSError, ValueError):
        app.logger.warning("uk_layoffs.json present but unreadable")
        return None
    _LAYOFFS_CACHE["mtime"] = mtime
    _LAYOFFS_CACHE["payload"] = payload
    return payload


def merge_divergence(divergence, rti):
    """Prefer parsed RTI over the pinned values, keeping the LFS side as-is.

    The LFS employees figure is not in the RTI workbook, so it stays pinned to
    the bulletin. Only the RTI half is upgraded when a good parse exists.
    """
    if not divergence:
        return None
    merged = dict(divergence)
    uk = (rti or {}).get("regions", {}).get("United Kingdom")
    if not uk:
        return merged
    merged.update({
        "rti_flash_change_on_year_august": uk["change_on_year"],
        "rti_level_august": uk["latest"],
        "rti_latest_period": uk["latest_period"],
        "rti_change_on_month": uk["change_on_month"],
        "rti_change_on_year_pct": uk["change_on_year_pct"],
        "manual": False,
        "rti_source_url": rti.get("source", {}).get("dataset_url"),
        "rti_workbook": rti.get("workbook"),
    })
    return merged


def labour_for_region(region_name):
    """Return the labour-market block for a UK region, or None."""
    payload = load_uk_labour()
    if not payload:
        return None
    region = payload.get("regions", {}).get(region_name)
    if not region:
        return None
    rti = load_uk_rti()
    rti_regions = (rti or {}).get("regions", {})
    return {
        "region": region_name,
        "lfs": region.get("lfs"),
        "aps": region.get("aps"),
        "claimant": region.get("claimant"),
        "rti": rti_regions.get(region_name),
        "rti_uk": rti_regions.get("United Kingdom"),
        "rti_source": (rti or {}).get("source"),
        "uk": payload.get("uk"),
        "national": payload.get("national"),
        "divergence": merge_divergence(payload.get("divergence"), rti),
        "sources": payload.get("sources"),
        "generated_at": payload.get("generated_at"),
    }


def load_country_data(country_code):
    data_path = os.path.join(
        os.path.dirname(__file__), "data", COUNTRIES[country_code]["data_file"]
    )
    with open(data_path, "r") as f:
        cities = json.load(f)
    for city in cities:
        city["score"] = compute_score(city["sectors"])
    return cities


def compute_score(sectors):
    weighted_sum = 0.0
    total_pct = 0.0
    for sector, pct in sectors.items():
        weight = SECTOR_WEIGHTS.get(sector, 0.3)
        weighted_sum += pct * weight
        total_pct += pct
    if total_pct == 0:
        return 0
    raw = weighted_sum / total_pct
    score = ((raw - 0.22) / 0.40) * 100
    return round(max(0, min(100, score)), 1)


@app.route("/")
def landing():
    return render_template(
        "landing.html",
        countries=COUNTRIES,
        meta_description="A historical city comparison using workforce composition and CopeCheck's heuristic sector-exposure index; not an official probability or job-loss forecast.",
    )


@app.route("/<country>/")
def country_index(country):
    if country not in COUNTRIES:
        abort(404)
    cities = load_country_data(country)

    sort_by = request.args.get("sort", "score")
    sort_dir = request.args.get("dir", "desc")

    if sort_by == "name":
        cities.sort(key=lambda c: c["name"], reverse=(sort_dir == "desc"))
    elif sort_by == "region":
        cities.sort(key=lambda c: c["region"], reverse=(sort_dir == "desc"))
    elif sort_by == "population":
        cities.sort(key=lambda c: c["population"], reverse=(sort_dir == "desc"))
    elif sort_by == "gva":
        cities.sort(key=lambda c: c.get("gva", 0), reverse=(sort_dir == "desc"))
    else:
        cities.sort(key=lambda c: c["score"], reverse=(sort_dir == "desc"))

    scored = load_country_data(country)
    scored.sort(key=lambda c: c["score"], reverse=True)
    rank_map = {c["slug"]: i + 1 for i, c in enumerate(scored)}

    return render_template(
        "country.html",
        country_code=country,
        country=COUNTRIES[country],
        cities=cities,
        rank_map=rank_map,
        sort_by=sort_by,
        sort_dir=sort_dir,
        total_cities=len(cities),
        uk_labour=load_uk_labour() if country == "uk" else None,
        meta_description=f"Heuristic AI-displacement exposure comparison for {COUNTRIES[country]['name']} cities. {len(cities)} historical workforce snapshots scored on a 0-100 relative index.",
    )


@app.route("/<country>/<city_slug>")
def city_detail(country, city_slug):
    if country not in COUNTRIES:
        abort(404)
    cities = load_country_data(country)
    cities.sort(key=lambda c: c["score"], reverse=True)
    rank_map = {c["slug"]: i + 1 for i, c in enumerate(cities)}

    city = next((c for c in cities if c["slug"] == city_slug), None)
    if not city:
        abort(404)

    sectors_display = []
    for key, pct in sorted(city["sectors"].items(), key=lambda x: x[1], reverse=True):
        sectors_display.append(
            {
                "key": key,
                "label": SECTOR_LABELS.get(key, key),
                "pct": pct,
                "weight": SECTOR_WEIGHTS.get(key, 0.3),
                "risk": SECTOR_RISK_TIER.get(key, "medium"),
                "contribution": round(pct * SECTOR_WEIGHTS.get(key, 0.3), 2),
            }
        )

    labour = labour_for_region(city["region"]) if country == "uk" else None

    return render_template(
        "city.html",
        country_code=country,
        country=COUNTRIES[country],
        city=city,
        rank=rank_map[city["slug"]],
        total_cities=len(cities),
        sectors=sectors_display,
        labour=labour,
        layoffs=load_uk_layoffs() if country == "uk" else None,
        meta_description=f"{city['name']} heuristic AI-displacement exposure score: {city['score']}/100. Ranked #{rank_map[city['slug']]} of {len(cities)} {COUNTRIES[country]['name']} cities in this historical comparison set.",
    )




ARTICLES = [
    {"url": "/articles/top-10-best-cities-ai-transition", "title": "10 Lowest-Scoring Cities in the Exposure Index", "description": "The lowest results in CopeCheck's historical heuristic sector-exposure comparison across six countries."},
    {"url": "/articles/top-10-worst-cities-ai-transition", "title": "10 Highest-Scoring Cities in the Exposure Index", "description": "The highest results in CopeCheck's historical heuristic sector-exposure comparison across six countries."},
]


@app.route("/articles/")
def articles_index():
    return render_template("articles_index.html", articles=ARTICLES,
        countries=COUNTRIES,
        meta_description="Historical city comparisons using CopeCheck's disclosed heuristic sector-exposure index.")


def _get_all_cities_ranked():
    """Load all cities from all countries, compute scores, return sorted."""
    all_cities = []
    for code, info in COUNTRIES.items():
        cities = load_country_data(code)
        for c in cities:
            c["country_code"] = code
            c["country_name"] = info["name"]
            c["flag"] = info["flag"]
            top3 = sorted(c["sectors"].items(), key=lambda x: x[1], reverse=True)[:3]
            c["top_sectors"] = [{"label": SECTOR_LABELS.get(s[0], s[0]), "pct": s[1]} for s in top3]
        all_cities.extend(cities)
    all_cities.sort(key=lambda c: c["score"])
    return all_cities


@app.route("/articles/top-10-best-cities-ai-transition")
def article_best():
    all_cities = _get_all_cities_ranked()
    best = all_cities[:10]
    for c in best:
        hr = sum(v for k, v in c["sectors"].items() if k in ["administrative_support","retail","manufacturing","financial_services","transport_storage"])
        low = sum(v for k, v in c["sectors"].items() if k in ["health","education","public_admin"])
        c["commentary"] = (
            f"With a heuristic exposure score of {c['score']}/100, {c['name']} ranks toward the "
            f"lower end of this comparison. {low:.1f}% of the bundled employment snapshot sits in "
            f"health, education, and public administration, which receive lower weights in this model. "
            f"{hr:.1f}% sits in sectors assigned higher exposure weights. This is a structural "
            f"screening result, not a forecast of how many jobs will disappear or when."
        )
    return render_template("article.html",
        countries=COUNTRIES,
        title="10 Lowest-Scoring Cities in the Exposure Index",
        subtitle="The lowest-scoring cities in CopeCheck's historical, heuristic sector-exposure comparison across 6 countries.",
        intro="These are the 10 cities with the lowest scores under CopeCheck's sector-exposure heuristic. The model gives lower weights to sectors such as healthcare, education, and public administration. A low score is not a safety forecast and does not establish how many jobs will change or when.",
        cities=best,
        article_type="best",
        meta_description="The 10 lowest-scoring cities in CopeCheck's historical heuristic sector-exposure comparison across six countries.")


@app.route("/articles/top-10-worst-cities-ai-transition")
def article_worst():
    all_cities = _get_all_cities_ranked()
    worst = all_cities[-10:][::-1]
    for c in worst:
        hr = sum(v for k, v in c["sectors"].items() if k in ["administrative_support","retail","manufacturing","financial_services","transport_storage"])
        c["commentary"] = (
            f"{c['name']} scores {c['score']}/100 on the heuristic exposure index, placing it among the "
            f"highest-scoring cities in this dataset. A combined {hr:.1f}% of employment sits in "
            f"sectors assigned higher heuristic exposure weights — retail, admin, manufacturing, "
            f"financial services, and transport. The result identifies concentration under this "
            f"model; it does not estimate a probability, timing, or number of jobs displaced."
        )
    return render_template("article.html",
        countries=COUNTRIES,
        title="10 Highest-Scoring Cities in the Exposure Index",
        subtitle="The highest-scoring cities in CopeCheck's historical, heuristic sector-exposure comparison.",
        intro="This historical comparison assigns higher heuristic exposure weights to retail, administrative support, manufacturing, financial services, and logistics. These are the 10 cities with the highest scores under that model. The ranking is a screening tool, not a forecast of job losses or their timing.",
        cities=worst,
        article_type="worst",
        meta_description="The 10 highest-scoring cities in CopeCheck's historical heuristic sector-exposure comparison across six countries.")



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

@app.route("/sitemap.xml")
def sitemap():
    pages = []
    base = "https://cities.copecheck.com"
    pages.append({"url": base + "/", "priority": "1.0"})
    for code in COUNTRIES:
        pages.append({"url": f"{base}/{code}/", "priority": "0.9"})
        cities = load_country_data(code)
        for city in cities:
            pages.append(
                {"url": f"{base}/{code}/{city['slug']}", "priority": "0.7"}
            )
    xml = render_template("sitemap.xml", pages=pages)
    return Response(xml, mimetype="application/xml")


@app.errorhandler(404)
def page_not_found(e):
    return render_template("404.html", countries=COUNTRIES), 404




# --- Newsletter subscribe proxy (beehiiv) ---
@app.route('/api/subscribe', methods=['POST'])
def api_newsletter_subscribe():
    """Proxy newsletter signups to beehiiv to avoid cross-origin blocks."""
    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:
        # The Cities venv does not include ``requests``.  Use the standard
        # library with a cookie jar so the public subscribe endpoint works
        # without adding an undeclared runtime dependency.
        from http.cookiejar import CookieJar
        from urllib.parse import urlencode
        from urllib.request import HTTPCookieProcessor, Request as URLRequest, build_opener

        opener = build_opener(HTTPCookieProcessor(CookieJar()))
        page_request = URLRequest(
            'https://copecheck.beehiiv.com',
            headers={'User-Agent': 'Mozilla/5.0'},
        )
        with opener.open(page_request, timeout=10) as page_response:
            page_text = page_response.read().decode('utf-8', 'replace')
        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': '/',
        }
        submit_request = URLRequest(
            'https://copecheck.beehiiv.com/create',
            data=urlencode(form).encode('utf-8'),
            headers={
                'User-Agent': 'Mozilla/5.0',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        )
        with opener.open(submit_request, timeout=10) as submit_response:
            status = submit_response.status
        if status < 400:
            return jsonify({'success': True, 'message': 'Subscribed!'})
        return jsonify({'error': 'Subscription failed', 'status': status}), 502
    except Exception as exc:
        app.logger.warning('Beehiiv subscription proxy failed: %s', type(exc).__name__)
        return jsonify({'error': 'Subscription service unavailable'}), 502



# --- 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, timezone as _timezone
    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': 'cities.copecheck.com',
        'ts': _dt.now(_timezone.utc).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:
            from urllib.request import Request as _URLRequest, urlopen as _urlopen

            notification = _URLRequest(
[redacted secret-like line]
                data=_json.dumps(entry).encode('utf-8'),
                headers={
                    'Content-Type': 'application/json',
                    'User-Agent': 'CopeCheck-Cities/1.0',
                },
                method='POST',
            )
            with _urlopen(notification, timeout=5):
                pass
        except Exception as exc:
            app.logger.warning('Feedback notification failed: %s', type(exc).__name__)
    threading.Thread(target=_notify, daemon=True).start()
    return jsonify({'success': True})

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

if __name__ == "__main__":
    app.run(debug=True, port=5020)


# ── 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
```
