---
type: "Source File"
title: "\"\"\"CopeCheck Layoffs — layoffs.copecheck.com\"\"\""
description: "\"\"\"CopeCheck Layoffs — layoffs.copecheck.com\"\"\" import json, os from flask import Flask, render_template, request, jsonify, Response from datetime import datetime from urllib.parse import parse_qsl, urlencode."
resource: "https://layoffs.copecheck.com"
tags: ["copecheck", "layoffs", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "layoffs"
source_path: "copecheck-layoffs/app.py"
---

# """CopeCheck Layoffs — layoffs.copecheck.com"""

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

```py
"""CopeCheck Layoffs — layoffs.copecheck.com"""
import json, os
from flask import Flask, render_template, request, jsonify, Response
from datetime import datetime
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

import re as _re

def slugify(text):
    """Convert company name to URL slug."""
    text = str(text).lower().strip()
    text = _re.sub(r"[^a-z0-9\s-]", "", text)
    text = _re.sub(r"[\s-]+", "-", text)
    return text.strip("-")



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



# Make slugify available in all templates
@app.context_processor
def inject_helpers():
    return dict(slugify=slugify)


DATA_DIR = os.path.join(os.path.dirname(__file__), "data")


def normalize_laid_off(value):
    """Return a safe integer count while preserving approximate source wording."""
    if value is None or isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return max(0, int(value))
    match = _re.search(r"\d[\d,]*", str(value))
    if not match:
        return None
    return int(match.group(0).replace(",", ""))


def load_data():
    with open(os.path.join(DATA_DIR, "layoffs.json")) as f:
        data = json.load(f)
    for section in ("major_2026", "major_2025", "scanned_2026", "scanned_2025", "uk_layoffs"):
        for entry in data.get(section, []):
            raw_count = entry.get("laid_off")
            if raw_count is not None and not isinstance(raw_count, (int, float)):
                entry.setdefault("laid_off_text", str(raw_count))
            entry["laid_off"] = normalize_laid_off(raw_count)
    return data

def load_oracle_verdicts():
    path = os.path.join(DATA_DIR, "oracle_verdicts.json")
    if os.path.exists(path):
        with open(path) as f:
            return json.load(f)
    return {}

def load_codex_oracle():
    path = os.path.join(DATA_DIR, "codex_oracle.json")
    if os.path.exists(path):
        with open(path) as f:
            return json.load(f)
    return {}

def filter_weak(entries):
    """Filter out entries where both laid_off and pct are None/null."""
    return [e for e in entries if e.get("laid_off") or e.get("pct")]


TRACKING_QUERY_KEYS = {
    "fbclid", "gclid", "mc_cid", "mc_eid", "oc", "ref", "ref_src",
    "utm_campaign", "utm_content", "utm_medium", "utm_source", "utm_term",
}


def canonical_source_url(value):
    """Normalise a source URL for identity without changing the displayed URL."""
    try:
        parts = urlsplit(str(value or "").strip())
        host = (parts.hostname or "").lower()
        parsed_port = parts.port
    except ValueError:
        return ""
    if not host:
        return ""
    if host.startswith("www."):
        host = host[4:]
    port = f":{parsed_port}" if parsed_port and parsed_port not in (80, 443) else ""
    path = parts.path.rstrip("/") or "/"
    query = urlencode(
        sorted(
            (key, val)
            for key, val in parse_qsl(parts.query, keep_blank_values=True)
            if key.lower() not in TRACKING_QUERY_KEYS
        )
    )
    return urlunsplit(("https", host + port, path, query, ""))


def deduplicate_claims(entries):
    """Collapse exact repeated claim captures without pretending to reconcile totals.

    Separate reports with different company/date/quantity claims remain separate.  The
    public site deliberately does not add these rows because aggregate articles,
    forward plans and overlapping company aliases can still describe the same people.
    """
    result = []
    grouped = {}
    for entry in filter_weak(entries):
        company = slugify(entry.get("company", ""))
        laid_off = entry.get("laid_off")
        quantity = (
            ("count", laid_off)
            if laid_off is not None
            else ("percent", _re.sub(r"[^0-9.]", "", str(entry.get("pct") or "")))
        )
        key = (
            company,
            str(entry.get("date") or "")[:7],
            quantity,
        )
        observation = dict(entry)
        observation["canonical_source_url"] = canonical_source_url(observation.get("source_url"))
        if key not in grouped:
            row = dict(observation)
            row["observations"] = [observation]
            grouped[key] = row
            result.append(row)
            continue
        row = grouped[key]
        row["observations"].append(observation)
        current_quality = (bool(row.get("source_url")), len(str(row.get("reason") or "")))
        candidate_quality = (bool(observation.get("source_url")), len(str(observation.get("reason") or "")))
        if candidate_quality > current_quality:
            observations = row["observations"]
            row.clear()
            row.update(observation)
            row["observations"] = observations
    for row in result:
        row["observation_count"] = len(row["observations"])
        row["source_observations"] = []
        seen_sources = set()
        for observation in row["observations"]:
            source_url = observation.get("source_url")
            source_key = observation.get("canonical_source_url") or source_url
            if not source_url or source_key in seen_sources:
                continue
            seen_sources.add(source_key)
            row["source_observations"].append({
                "url": source_url,
                "label": observation.get("source") or "source report",
            })
    return result


def claim_metrics(entries, data):
    sourced = sum(bool(entry.get("canonical_source_url")) for entry in entries)
    automated = sum(entry.get("added_by") == "scanner" for entry in entries)
    return {
        "unique_claims": len(entries),
        "source_linked_claims": sourced,
        "automated_claims": automated,
        "ai_attributed_claims": sum(bool(entry.get("ai_driven")) for entry in entries),
        "last_scan": data.get("meta", {}).get("last_scan") or data.get("meta", {}).get("last_updated") or "unknown",
    }

def group_stories(entries):
    """Group related layoff stories by company name (case-insensitive)."""
    groups = {}
    for entry in entries:
        key = entry["company"].lower().strip()
        # Normalize common variations
        for suffix in [" inc", " inc.", " corp", " corp.", " ltd", " ltd.", " llc", " plc"]:
            if key.endswith(suffix):
                key = key[:-len(suffix)].strip()
        if key not in groups:
            groups[key] = {
                "company": entry["company"],
                "entries": [],
                "total_laid_off": 0,
                "key": key,
            }
        groups[key]["entries"].append(entry)
        groups[key]["total_laid_off"] += entry.get("laid_off", 0) or 0
        # Keep the most complete company name
        if len(entry["company"]) > len(groups[key]["company"]):
            groups[key]["company"] = entry["company"]
    return list(groups.values())

COPECHECK_SITES = [
    ("CopeCheck", "https://copecheck.com"),
    ("UK", "https://uk.copecheck.com"),
    ("Countries", "https://countries.copecheck.com"),
    ("EU", "https://eu.copecheck.com"),
    ("Policy", "https://policy.copecheck.com"),
    ("Cities", "https://cities.copecheck.com"),
    ("Layoffs", "https://layoffs.copecheck.com"),
    ("Careers", "https://careers.copecheck.com"),
    ("Quiz", "https://quiz.copecheck.com"),
    ("Feedback", "https://copecheck.com/contact?from=https://layoffs.copecheck.com"),
]

@app.route("/")
def index():
    data = load_data()
    verdicts = load_oracle_verdicts()
    # This is a source-claim ledger, not an additive count of affected people.
    all_2026 = deduplicate_claims(data.get("major_2026", []) + data.get("scanned_2026", []))
    all_2025 = deduplicate_claims(data.get("major_2025", []) + data.get("scanned_2025", []))
    data["all_2026"] = sorted(all_2026, key=lambda x: x.get("laid_off") or 0, reverse=True)
    data["all_2025"] = sorted(all_2025, key=lambda x: x.get("laid_off") or 0, reverse=True)
    data["claim_metrics"] = claim_metrics(data["all_2026"], data)
    # Group stories for display
    data["groups_2026"] = group_stories(data["all_2026"])
    data["groups_2026"].sort(key=lambda g: g["total_laid_off"], reverse=True)
    return render_template("index.html", data=data, verdicts=verdicts, sites=COPECHECK_SITES)

@app.route("/timeline/")
def timeline():
    data = load_data()
    verdicts = load_oracle_verdicts()
    all_entries = deduplicate_claims(
        data.get("major_2026", []) + data.get("scanned_2026", []) +
        data.get("major_2025", []) + data.get("scanned_2025", [])
    )
    # Sort by date descending (newest layoff first)
    all_entries.sort(key=lambda x: x.get("date", "2025-01"), reverse=True)
    return render_template("timeline.html", entries=all_entries, data=data, verdicts=verdicts, sites=COPECHECK_SITES)

@app.route("/oracle/<job_id>/")
def oracle_detail(job_id):
    entries = load_codex_oracle()
    entry = entries.get(job_id)
    if not entry:
        return render_template("404.html"), 404
    return render_template("oracle_detail.html", entry=entry, sites=COPECHECK_SITES, data=load_data())

@app.route("/us/")
def us_layoffs():
    data = load_data()
    verdicts = load_oracle_verdicts()
    all_2026 = deduplicate_claims(data.get("major_2026", []) + data.get("scanned_2026", []))
    all_2025 = deduplicate_claims(data.get("major_2025", []) + data.get("scanned_2025", []))
    data["claim_metrics"] = claim_metrics(all_2026, data)
    us_2026 = sorted([l for l in all_2026 if l.get("country") == "US"], key=lambda x: x.get("laid_off") or 0, reverse=True)
    us_2025 = sorted([l for l in all_2025 if l.get("country") == "US"], key=lambda x: x.get("laid_off") or 0, reverse=True)
    data["country_claim_metrics"] = claim_metrics(us_2026, data)
    return render_template("country.html",
                           data=data,
                           country_name="United States",
                           country_code="us",
                           layoffs_2026=us_2026,
                           layoffs_2025=us_2025,
                           verdicts=verdicts,
                           sites=COPECHECK_SITES)

@app.route("/uk/")
def uk_layoffs():
    data = load_data()
    verdicts = load_oracle_verdicts()
    return render_template("uk.html", data=data, verdicts=verdicts, sites=COPECHECK_SITES)

@app.route("/hidden/")
def hidden_layoffs():
    data = load_data()
    return render_template("hidden.html", data=data, sites=COPECHECK_SITES)


@app.route("/submit/")
def submit_page():
    data = load_data()
    return render_template("submit.html", data=data, sites=COPECHECK_SITES)

@app.route("/api/submit", methods=["POST"])
def api_submit():
    import re
    from datetime import datetime
    body = request.get_json(force=True)
    url = (body.get("url") or "").strip()
    note = (body.get("note") or "").strip()

    if not url:
        return jsonify({"error": "URL is required"}), 400

    # Basic URL validation
    if not re.match(r'^https?://', url):
        return jsonify({"error": "Please enter a valid URL starting with http:// or https://"}), 400

    if len(url) > 2000:
        return jsonify({"error": "URL too long"}), 400

    submissions_path = os.path.join(DATA_DIR, "submissions.json")
    submissions = []
    if os.path.exists(submissions_path):
        with open(submissions_path) as f:
            submissions = json.load(f)

    # Check for duplicate
    existing_urls = {s["url"] for s in submissions}
    if url in existing_urls:
        return jsonify({"error": "This URL has already been submitted"}), 409

    submissions.append({
        "url": url,
        "note": note,
        "submitted_at": datetime.utcnow().isoformat() + "Z",
        "status": "pending"
    })

    with open(submissions_path, "w") as f:
        json.dump(submissions, f, indent=2)

    return jsonify({"ok": True, "message": "URL submitted for processing"})



@app.route("/layoff/<slug>/")
def layoff_detail(slug):
    data = load_data()
    verdicts = load_oracle_verdicts()

    all_entries = deduplicate_claims(
        data.get("major_2026", []) + data.get("scanned_2026", []) +
        data.get("major_2025", []) + data.get("scanned_2025", []) +
        data.get("uk_layoffs", [])
    )

    # Find best matching entry by slug
    entry = None
    for e in all_entries:
        if slugify(e.get("company", "")) == slug:
            entry = e
            break

    if not entry:
        data = load_data()
        return render_template("404.html", data=data, sites=COPECHECK_SITES), 404

    # Look up oracle verdict
    verdict = verdicts.get(slug) or verdicts.get(entry["company"].lower().strip())

    return render_template(
        "layoff_detail.html",
        entry=entry,
        verdict=verdict,
        data=data,
        sites=COPECHECK_SITES,
    )

@app.route("/california-tracker/")
def california_tracker():
    import json, os
    data_path = os.path.join(os.path.dirname(__file__), "data", "cait_parsed.json")
    with open(data_path) as f:
        chart_data = json.load(f)
    return render_template("california.html", chart_data=chart_data, sites=COPECHECK_SITES, data=load_data())

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

@app.route("/sitemap.xml")
def sitemap():
    pages = [
        {"loc": "https://layoffs.copecheck.com/", "priority": "1.0"},
        {"loc": "https://layoffs.copecheck.com/us/", "priority": "0.8"},
        {"loc": "https://layoffs.copecheck.com/uk/", "priority": "0.8"},
        {"loc": "https://layoffs.copecheck.com/hidden/", "priority": "0.8"},
        {"loc": "https://layoffs.copecheck.com/timeline/", "priority": "0.7"},
    ]
    return render_template("sitemap.xml", pages=pages), 200, {"Content-Type": "application/xml"}

@app.errorhandler(404)
def page_not_found(e):
    data = load_data()
    return render_template("404.html", data=data, sites=COPECHECK_SITES), 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."""
    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': 'layoffs.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})


# --- Job Safety Checker API (proxied from careers site) ---
@app.route('/api/job-safety')
def api_job_safety():
    """Proxy job safety check to careers.copecheck.com API."""
    import requests as _req
    q = request.args.get('q', '').strip()
    if not q or len(q) < 2:
        return jsonify({'results': []})
    try:
        resp = _req.get(f'http://localhost:8103/api/job-safety?q={q}', timeout=10)
        if resp.status_code == 200:
            data = resp.json()
            # Rewrite detail_url to point to careers site
            for r in data.get('results', []):
                if r.get('detail_url'):
                    r['detail_url'] = 'https://careers.copecheck.com' + r['detail_url']
            return jsonify(data)
    except Exception as e:
        print(f"Job safety proxy error: {e}")
    return jsonify({'results': [], 'error': 'Could not reach careers database'})

@app.route('/ai-disclosure')
def ai_disclosure():
    return render_template('ai_disclosure.html', data=load_data(), sites=COPECHECK_SITES)

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