---
type: "Source File"
title: "\"\"\""
description: "\"\"\" CopeCheck Cities — one-way snapshot of UK layoffs from copecheck-layoffs. Deliberate architecture: this script READS the layoffs service's data file and writes a private snapshot into this site's own data."
resource: "https://cities.copecheck.com"
tags: ["copecheck", "cities", "source-file", "py"]
timestamp: "2026-09-25T22:06:34Z"
site: "cities"
source_path: "copecheck-cities/layoffs_sync.py"
---

# """

Source path: `copecheck-cities/layoffs_sync.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-25T22:06:34Z`

```py
"""
CopeCheck Cities — one-way snapshot of UK layoffs from copecheck-layoffs.

Deliberate architecture: this script READS the layoffs service's data file and
writes a private snapshot into this site's own data directory.  The Flask app
never reads the layoffs service, never calls it over HTTP, and never imports
from it.  Consequences:

  * no circular dependency between the two sites;
  * if copecheck-layoffs is down or mid-write, cities just serves the last
    good snapshot;
  * if this snapshot is missing entirely, the city template omits the block.

IMPORTANT — what this does NOT do.  The layoffs dataset has no city or
location field; the finest geography it records is `country`.  So entries are
NOT matched to individual cities, because any such match would be inferred
rather than sourced.  The snapshot is UK-wide and the template labels it that
way.

The upstream dataset also carries `aggregate_status: withheld` and warns that
source claims "may be syndicated, aggregate, planned, aliased or overlapping
and cannot be added as distinct people".  This script therefore never sums
`laid_off` and never emits a total.

Writes data/uk_layoffs.json.  Run: venv/bin/python layoffs_sync.py
"""

import json
import logging
import os
from datetime import datetime, timezone

log = logging.getLogger("cities.layoffs")

HERE = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(HERE, "data")
OUT_PATH = os.path.join(DATA_DIR, "uk_layoffs.json")

SOURCE_PATH = os.path.join(
    os.path.dirname(HERE), "copecheck-layoffs", "data", "layoffs.json"
)

UK_VALUES = {"uk", "united kingdom", "gb", "great britain"}
MAX_ENTRIES = 12


class LayoffsUnavailable(RuntimeError):
    pass


def _is_uk(entry):
    return (entry.get("country") or "").strip().lower() in UK_VALUES


def _clean(entry):
    """Keep only sourced, attributable fields. Drop anything we can't cite."""
    if not entry.get("source_url"):
        return None
    # Upstream flags descriptive placeholders rather than deleting them
    # ("biggest UK vape wholesaler"). Those must never publish here.
    if entry.get("company_valid") is False:
        return None
    laid_off = entry.get("laid_off")
    try:
        laid_off = int(laid_off) if laid_off is not None else None
    except (TypeError, ValueError):
        laid_off = None
    return {
        "company": entry.get("company"),
        "laid_off": laid_off,
        "date": entry.get("date"),
        "sector": entry.get("sector"),
        "reason": (entry.get("reason") or "")[:400] or None,
        "ai_driven": bool(entry.get("ai_driven")),
        "source": entry.get("source"),
        "source_url": entry.get("source_url"),
        "unverified": entry.get("verification_status") == "unverified_auto",
    }


def build():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")

    if not os.path.exists(SOURCE_PATH):
        raise LayoffsUnavailable(f"layoffs data not found at {SOURCE_PATH}")
    try:
        with open(SOURCE_PATH, "r") as f:
            src = json.load(f)
    except (OSError, ValueError) as exc:
        # A partial read mid-write lands here; keeping the old snapshot is right.
        raise LayoffsUnavailable(f"layoffs data unreadable: {exc}") from exc

    scanned = src.get("scanned_2026") or []
    if not isinstance(scanned, list):
        raise LayoffsUnavailable("scanned_2026 is not a list")

    uk = [e for e in scanned if _is_uk(e)]
    cleaned = [c for c in (_clean(e) for e in uk) if c]
    # Most recent first; entries without a date sort last.
    cleaned.sort(key=lambda c: c.get("date") or "", reverse=True)

    verified = [c for c in cleaned if not c["unverified"]]
    ai_driven = [c for c in verified if c["ai_driven"]]

    payload = {
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "scope": "United Kingdom (country-level; the upstream dataset records no city or location field)",
        "upstream_last_updated": (src.get("meta") or {}).get("last_updated"),
        "upstream_last_scan": (src.get("meta") or {}).get("last_scan"),
        "entries": verified[:MAX_ENTRIES],
        "ai_driven_recent": ai_driven[:6],
        "counts": {
            "uk_entries_available": len(cleaned),
            "uk_entries_verified": len(verified),
            "uk_entries_ai_driven": len(ai_driven),
        },
        "aggregate_note": (src.get("meta") or {}).get("aggregate_note"),
        "source_note": (src.get("meta") or {}).get("source_note"),
        "site": {
            "name": "CopeCheck Layoffs",
            "url": "https://layoffs.copecheck.com/uk/",
        },
        "caveat": (
            "Counts are individual reported events, not a national total. The "
            "upstream tracker withholds aggregates because source claims may be "
            "syndicated, aggregate, planned, aliased or overlapping. These are "
            "UK-wide and are not attributed to this city."
        ),
    }

    os.makedirs(DATA_DIR, exist_ok=True)
    tmp = OUT_PATH + ".tmp"
    with open(tmp, "w") as f:
        json.dump(payload, f, indent=1)
    os.replace(tmp, OUT_PATH)
    log.info(
        "wrote %s — %d UK entries (%d verified, %d AI-driven)",
        OUT_PATH, len(cleaned), len(verified), len(ai_driven),
    )
    return payload


if __name__ == "__main__":
    try:
        build()
    except LayoffsUnavailable as exc:
        logging.warning("layoffs snapshot not refreshed, keeping previous: %s", exc)
        raise SystemExit(0)  # not an error: the city site degrades gracefully
```
