---
type: "Source File"
title: "\"\"\""
description: "\"\"\" CopeCheck Cities — regenerate a city's narrative fields against measured data. This is an EXTENDED PASS in the established sense: it ADDS or replaces narrative prose only. It never computes, touches, or writes a."
resource: "https://cities.copecheck.com"
tags: ["copecheck", "cities", "source-file", "py"]
timestamp: "2026-10-20T10:43:18Z"
site: "cities"
source_path: "copecheck-cities/generate_city_narrative.py"
---

# """

Source path: `copecheck-cities/generate_city_narrative.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-10-20T10:43:18Z`

```py
"""
CopeCheck Cities — regenerate a city's narrative fields against measured data.

This is an EXTENDED PASS in the established sense: it ADDS or replaces
narrative prose only. It never computes, touches, or writes a score, and it
verifies afterwards that every score input is byte-identical to what it read.
If anything that feeds compute_score() has moved, the run aborts and the file
is left alone.

It reuses the existing CopeCheck model chain (copecheck-uk/oracle_uk.py:
MiniMax -> OpenRouter) rather than introducing a new one.
API keys are read from the environment by that module; this script never reads,
logs, or writes a key value.

Usage:
    set -a; . /etc/copecheck/env/copecheck-uk.env; set +a
    venv/bin/python generate_city_narrative.py --slug london
    venv/bin/python generate_city_narrative.py --slug london --dry-run
"""

import argparse
import copy
import json
import logging
import os
import sys
from datetime import datetime, timezone

HERE = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(HERE, "data")
BACKUP_DIR = os.path.join(DATA_DIR, "narrative_backups")

UK_SITE = os.path.join(os.path.dirname(HERE), "copecheck-uk")

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

NARRATIVE_FIELDS = ("oracle_soft", "oracle_brutal", "advice_soft", "advice_brutal")

# Everything that feeds compute_score(), plus identity. Must never change.
PROTECTED_FIELDS = ("name", "slug", "region", "population", "sectors", "gva")

SYSTEM = """You write for CopeCheck Cities, which publishes a structural
AI-displacement exposure index for UK cities. Your job is the narrative
commentary that sits alongside measured official statistics.

Absolute rules:
1. Use ONLY figures present in the FACTS block. Never invent, estimate,
   round differently, extrapolate, or introduce any number not given to you.
   If you want a number you do not have, write around it.
1a. Do NOT derive new arithmetic from the given figures: no ratios,
   percentages, shares, offsets, or "accounts for X of Y" claims that are not
   stated in the FACTS block. In particular, a rise in one group and a fall in
   a total are NOT an "offset" and one does not "account for" the other —
   describe each as given. Any comparison you make must already be written out
   in the FACTS block.
1b. Do NOT assert causation, mechanism, or attribution that the FACTS block
   does not state. Two facts appearing together is not evidence that one
   caused, explains, located or targeted the other. In particular: the
   structural sector weights describe which industries are exposed, and the
   measured labour statistics describe who is unemployed, claiming or
   inactive — the data contains NO sector breakdown of claimants, of the
   young, or of any other demographic group, so you may never say or imply
   that a demographic change is landing "where the exposure flags predicted",
   "precisely where you would expect", "in exactly the exposed sectors", or
   any equivalent. You may place two facts side by side and note that they
   are consistent or uncomfortable; you may not claim one explains the other.
   If a causal story is tempting, say explicitly that the data does not
   identify the cause.
2. Do not state or imply a displacement probability, a job-loss forecast, or
   a date by which jobs will go. The exposure score is a structural
   comparison, not a prediction.
3. Do not contradict the FACTS block. If the measured data complicates a
   comfortable story, say so plainly.
4. No invented quotes, named individuals, companies, or specific employer
   decisions.

Return STRICT JSON with exactly these four keys and no other text:
  oracle_soft    - measured, analytical. 150-200 words.
  oracle_brutal  - the same facts, satirical and blunt. 150-200 words.
  advice_soft    - practical advice for local leaders. 120-160 words.
  advice_brutal  - satirical counterpart to the advice. 120-160 words.
"""

USER_TEMPLATE = """FACTS for {name} ({region}), as of {today}.

STRUCTURAL (the exposure index input — historical workforce snapshot):
  Exposure score: {score}/100, ranked {rank} of {total} UK cities in this set
  Baseline population: {population}
  Sector employment shares (%): {sectors}
  Highest-weighted sectors in this city: {top_exposed}

MEASURED (official statistics for the {region} region, not the city alone):
{measured}

WHAT MATTERS MOST IN THIS DATA:
{emphasis}

Write the four fields. The narrative must engage directly with the MEASURED
block — especially the point flagged under WHAT MATTERS MOST — rather than
resting on the structural picture alone.
"""


def _fmt(n):
    return f"{int(n):,}"


def build_facts(city, rank, total, labour, rti):
    lines, emphasis = [], []

    lfs = (labour or {}).get("lfs")
    if lfs:
        lines.append(
            f"  LFS ({lfs['period']}, seasonally adjusted): unemployment "
            f"{lfs['unemployment_rate_16_plus']}% (change on year "
            f"{lfs['unemployment_rate_change_on_year']:+} pp); employment "
            f"{lfs['employment_rate_16_64']}% ({lfs['employment_rate_change_on_year']:+} pp); "
            f"inactivity {lfs['inactivity_rate_16_64']}% "
            f"({lfs['inactivity_rate_change_on_year']:+} pp)."
        )
        if lfs.get("unemployment_rank") == 1:
            lines.append(
                f"  This is the HIGHEST unemployment rate of the "
                f"{lfs['unemployment_rank_of']} UK regions and countries."
            )
            emphasis.append(
                "This region has the highest unemployment rate in the UK, and all "
                "three headline rates moved the wrong way over the year."
            )

    uk_lfs = ((labour or {}).get("uk") or {}).get("lfs")
    if uk_lfs:
        lines.append(
            f"  UK average same period: unemployment {uk_lfs['unemployment_rate_16_plus']}%, "
            f"employment {uk_lfs['employment_rate_16_64']}%, "
            f"inactivity {uk_lfs['inactivity_rate_16_64']}%."
        )

    c = (labour or {}).get("claimant")
    if c and c.get("count"):
        lines.append(
            f"  Claimant count ({c['latest_period']}, not seasonally adjusted): "
            f"{_fmt(c['count'])} people, {c.get('rate')}% of economically active residents."
        )
        if c.get("count_year_ago"):
            d = int(c["count"] - c["count_year_ago"])
            lines.append(
                f"  Claimant count change on {c['year_ago_period']}: {d:+,} "
                f"({'down' if d < 0 else 'up'})."
            )
        if c.get("youth_count") and c.get("youth_count_year_ago"):
            yd = int(c["youth_count"] - c["youth_count_year_ago"])
            lines.append(
                f"  Claimants aged 16-24: {_fmt(c['youth_count'])}, {yd:+,} on the year "
                f"({'down' if yd < 0 else 'up'})."
            )
            if c.get("count_year_ago"):
                d = int(c["count"] - c["count_year_ago"])
                # State the 25+ residual explicitly so the narrative never has
                # to derive it (and never mis-derives it as an "offset").
                older = d - yd
                lines.append(
                    f"  Implied claimants aged 25 and over: {older:+,} on the year. "
                    f"(The total change and the 16-24 change are in OPPOSITE "
                    f"directions; the 16-24 rise does not offset or account for any "
                    f"part of the total fall — the over-25 group fell by more than "
                    f"the total, and the youth rise partly masked that.)"
                )
                if d < 0 < yd:
                    emphasis.append(
                        f"THE CENTRAL POINT: the overall claimant count FELL by "
                        f"{abs(d):,} over the year while youth claimants ROSE by "
                        f"{yd:,}, with claimants aged 25+ falling by {abs(older):,}. "
                        f"The aggregate is improving because older workers are "
                        f"leaving the count faster than young people are joining it. "
                        f"An account that cites only the headline number misses this "
                        f"entirely, and the split is the most important thing in this "
                        f"data. Do not describe the youth rise as offsetting the fall."
                    )

    if rti:
        lines.append(
            f"  Payrolled employees (HMRC PAYE RTI, {rti['latest_period']}): "
            f"{_fmt(rti['latest'])}, change on year {rti['change_on_year']:+,} "
            f"({rti['change_on_year_pct']}%)."
        )
    uk_rti = (labour or {}).get("rti_uk")
    if rti and uk_rti:
        lines.append(
            f"  UK payrolled employees change on year: {uk_rti['change_on_year']:+,} "
            f"({uk_rti['change_on_year_pct']}%)."
        )
        if rti["change_on_year_pct"] < uk_rti["change_on_year_pct"]:
            emphasis.append(
                f"Payrolled employment here is falling FASTER than the UK average "
                f"({rti['change_on_year_pct']}% against {uk_rti['change_on_year_pct']}%)."
            )

    d = (labour or {}).get("divergence")
    if d:
        lines.append(
            f"  UK-wide source divergence: HMRC payroll records show employees down "
            f"{abs(d['rti_change_on_year_july']):,} over the year to July 2026, while the "
            f"Labour Force Survey shows employees UP {d['lfs_employees_change_on_year']:,}. "
            f"ONS says RTI is currently the more reliable measure and attributes much of "
            f"the survey's rise to improved response rather than hiring."
        )

    nat = (labour or {}).get("national") or {}
    if nat.get("vacancies"):
        lines.append(
            f"  UK vacancies: {_fmt(nat['vacancies']['value'] * 1000)} "
            f"({nat['vacancies']['period']}) — lowest outside the pandemic since 2014."
        )
    if nat.get("youth_unemployment_rate"):
        lines.append(
            f"  UK youth unemployment rate: {nat['youth_unemployment_rate']['value']}% "
            f"({nat['youth_unemployment_rate']['period']}) — an 11-year high."
        )

    if not emphasis:
        emphasis.append("Engage with the measured figures rather than the structure alone.")

    return "\n".join(lines) or "  (no measured data available)", "\n".join(
        f"  - {e}" for e in emphasis
    )


def parse_response(raw):
    text = raw.strip()
    if text.startswith("```"):
        text = text.split("```")[1]
        if text.startswith("json"):
            text = text[4:]
    start, end = text.find("{"), text.rfind("}")
    if start == -1 or end == -1:
        raise ValueError(f"no JSON object in model response: {raw[:200]}")
    obj = json.loads(text[start:end + 1])
    missing = [f for f in NARRATIVE_FIELDS if not obj.get(f)]
    if missing:
        raise ValueError(f"model omitted fields: {missing}")
    for f in NARRATIVE_FIELDS:
        if not isinstance(obj[f], str) or len(obj[f]) < 200:
            raise ValueError(f"field {f} too short or not a string")
    return {f: obj[f].strip() for f in NARRATIVE_FIELDS}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--slug", required=True)
    ap.add_argument("--country", default="uk")
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()

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

    import app as cities_app  # compute_score, SECTOR_WEIGHTS, loaders

    path = os.path.join(DATA_DIR, f"{args.country}.json")
    with open(path, "r") as f:
        cities = json.load(f)

    idx = next((i for i, c in enumerate(cities) if c["slug"] == args.slug), None)
    if idx is None:
        raise SystemExit(f"city {args.slug!r} not found in {args.country}.json")

    before = copy.deepcopy(cities[idx])
    city = cities[idx]

    scored = [dict(c, score=cities_app.compute_score(c["sectors"])) for c in cities]
    scored.sort(key=lambda c: c["score"], reverse=True)
    rank = next(i + 1 for i, c in enumerate(scored) if c["slug"] == args.slug)
    score_before = cities_app.compute_score(city["sectors"])

    labour = cities_app.labour_for_region(city["region"])
    rti = (labour or {}).get("rti")

    top_exposed = sorted(
        city["sectors"].items(),
        key=lambda kv: kv[1] * cities_app.SECTOR_WEIGHTS.get(kv[0], 0.3),
        reverse=True,
    )[:4]

    measured, emphasis = build_facts(city, rank, len(cities), labour, rti)
    user = USER_TEMPLATE.format(
        name=city["name"], region=city["region"],
        today=datetime.now(timezone.utc).date().isoformat(),
        score=score_before, rank=rank, total=len(cities),
        population=_fmt(city["population"]),
        sectors=", ".join(f"{k} {v}" for k, v in sorted(
            city["sectors"].items(), key=lambda kv: -kv[1])),
        top_exposed=", ".join(
            f"{cities_app.SECTOR_LABELS.get(k, k)} ({v}%)" for k, v in top_exposed),
        measured=measured, emphasis=emphasis,
    )

    log.info("facts assembled for %s:\n%s\n%s", city["name"], measured, emphasis)
    if args.dry_run:
        print(user)
        return

    # Append (not prepend) so the local `app` module already imported above is
    # not shadowed by copecheck-uk's own app.py.
    sys.path.append(UK_SITE)
    import oracle_uk  # existing model chain; reads keys from env itself
    raw, provider = oracle_uk._call_ai(SYSTEM, user, timeout=180)
    log.info("model responded via %s (%d chars)", provider, len(raw))
    new_fields = parse_response(raw)

    os.makedirs(BACKUP_DIR, exist_ok=True)
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    backup_path = os.path.join(BACKUP_DIR, f"{args.slug}-{stamp}.json")
    with open(backup_path, "w") as f:
        json.dump({
            "slug": args.slug,
            "backed_up_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
            "reason": "extended narrative pass against measured ONS data",
            "previous": {f: before.get(f) for f in NARRATIVE_FIELDS},
        }, f, indent=1)
    log.info("previous narrative backed up to %s", backup_path)

    city.update(new_fields)
    city["narrative_generated_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
    city["narrative_provider"] = provider
    city["narrative_basis"] = (
        "ONS regional LFS, claimant count and HMRC PAYE RTI, as cited on this page"
    )

    # --- the guarantee: nothing that feeds the score may have moved ---
    for field in PROTECTED_FIELDS:
        if json.dumps(before.get(field), sort_keys=True) != json.dumps(
            city.get(field), sort_keys=True
        ):
            raise SystemExit(f"ABORT: protected field {field!r} changed — file not written")
    score_after = cities_app.compute_score(city["sectors"])
    if score_after != score_before:
        raise SystemExit(
            f"ABORT: score moved {score_before} -> {score_after} — file not written"
        )
    if "score" in city:
        raise SystemExit("ABORT: a score key was written into the data file")

    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(cities, f, indent=1, ensure_ascii=False)
    os.replace(tmp, path)
    log.info(
        "wrote %s — %s narrative regenerated, score unchanged at %s",
        path, city["name"], score_after,
    )


if __name__ == "__main__":
    main()
```
