"""Turn the processed data into the website's data files and one static page per job. Run: .venv/bin/python research/build_site.py (after build_dataset.py and analysis.py) Writes site/data/*.json, site/jobs//index.html, site/jobs/index.html and site/sitemap.xml. Pages are plain HTML so they load fast, work without JavaScript, and can be found by search engines. """ import html import json import re from pathlib import Path import numpy as np import pandas as pd ROOT = Path(__file__).resolve().parent.parent SITE = ROOT / "site" BASE_URL = "https://overexposed-eta.vercel.app" ASSET_V = "1" MAJOR = {"11": "Management", "13": "Business and finance", "15": "Computer and math", "17": "Engineering and architecture", "19": "Science", "21": "Community and social service", "23": "Legal", "25": "Education", "27": "Arts, media and sports", "29": "Healthcare practitioners", "31": "Healthcare support", "33": "Protective service", "35": "Food service", "37": "Cleaning and grounds", "39": "Personal care", "41": "Sales", "43": "Office and admin", "45": "Farming, fishing and forestry", "47": "Construction", "49": "Repair and maintenance", "51": "Production", "53": "Transportation"} # CPI-U, U.S. city average, not seasonally adjusted (BLS series CUUR0000SA0), for each May. CPI = {2019: 256.092, 2022: 292.296, 2025: 321.465} e = html.escape def slugify(title): s = title.lower().replace("&", "and") s = re.sub(r"[^a-z0-9]+", "-", s).strip("-") return s[:80].rstrip("-") def pct(x, digits=0, sign=True): if x is None or (isinstance(x, float) and np.isnan(x)): return "n/a" v = x * 100 s = f"{v:+.{digits}f}%" if sign else f"{v:.{digits}f}%" return s.replace("-", "−") def num(x): return "n/a" if pd.isna(x) else f"{int(round(x)):,}" def money(x): return "n/a" if pd.isna(x) else f"${int(round(x)):,}" def weighted_pct_rank(values, weights, v): """Share of workers in jobs with a lower score, so "more exposed than 80% of workers" is literal.""" m = ~np.isnan(values) return float(weights[m][values[m] < v].sum() / weights[m].sum()) def load(): df = pd.read_csv(ROOT / "data" / "processed" / "occupations.csv", dtype={"soc": str, "major": str}).set_index("soc") tasks = pd.read_csv(ROOT / "data" / "processed" / "tasks.csv", dtype={"soc": str}) results = json.loads((ROOT / "results" / "results.json").read_text()) slugs, seen = {}, set() for soc, t in df.title.items(): s = slugify(t) if s in seen: s = f"{s}-{soc.replace('-', '')}" seen.add(s) slugs[soc] = s df["slug"] = pd.Series(slugs) return df, tasks, results def field_growth(df): d = df.dropna(subset=["emp_2022", "emp_2025"]) g = d.groupby("major").apply(lambda s: s.emp_2025.sum() / s.emp_2022.sum() - 1, include_groups=False) return g, d.emp_2025.sum() / d.emp_2022.sum() - 1 def story_data(df): """Compact rows for the scroll story. Within-field values subtract each field's employment-weighted average, which is exactly what the 'compare within the same field' regression does.""" d = df.dropna(subset=["observed", "g_post", "emp_2022"]).copy() for col, out in [("observed", "xo"), ("g_post", "yo")]: mean = d.groupby("major").apply(lambda s: np.average(s[col], weights=s.emp_2022), include_groups=False) d[out] = d[col] - d.major.map(mean) # Thirds of each field by the 2023 forecast, on the same sample as analysis.tercile_index # (jobs with a forecast and employment in every year): 0 = least exposed, 2 = most. full = df.dropna(subset=[f"emp_{y}" for y in range(2019, 2026)] + ["beta_gpt4", "observed"]).copy() r = full.groupby("major").beta_gpt4.rank(pct=True) terc = pd.Series(np.select([r > 2 / 3, r > 1 / 3], [2, 1], 0), index=full.index) rows = [] for soc, r in d.iterrows(): rows.append([soc, r.title, r.slug, int(r.emp_2022), round(r.observed, 4), None if pd.isna(r.beta_gpt4) else round(r.beta_gpt4, 3), None if pd.isna(r.g_pre) else round(r.g_pre, 4), round(r.g_post, 4), r.major, round(r.xo, 4), round(r.yo, 4), int(terc[soc]) if soc in terc.index else None, int(r.emp_2025)]) return {"cols": ["soc", "title", "slug", "emp", "obs", "beta", "gpre", "gpost", "major", "xo", "yo", "terc", "emp25"], "majors": MAJOR, "rows": rows} def search_data(df): out = [] for soc, r in df.iterrows(): alts = [] if pd.isna(r.alt_titles) else r.alt_titles.split("|") out.append([r.slug, r.title, "|".join(alts[:30]), 0 if pd.isna(r.emp_2025) else int(r.emp_2025)]) return out def sparkline(years, values, w=560, h=150): pts = [(y, v) for y, v in zip(years, values) if not pd.isna(v)] if len(pts) < 2: return "" vs = [v for _, v in pts] lo, hi = min(vs), max(vs) pad = (hi - lo) * 0.18 or hi * 0.05 or 1 lo, hi = lo - pad, hi + pad X = lambda y: 44 + (y - years[0]) / (years[-1] - years[0]) * (w - 88) Y = lambda v: 18 + (1 - (v - lo) / (hi - lo)) * (h - 48) path = " ".join(f"{'M' if i == 0 else 'L'}{X(y):.1f},{Y(v):.1f}" for i, (y, v) in enumerate(pts)) dots = "".join( f'' f'{int(v):,}' for y, v in pts) xl = "".join(f'{y}' for y, _ in pts) cut = X(2022.55) return (f'' f'' f'ChatGPT' f'{dots}{xl}') def meter(label, value, rank, note): if value is None or pd.isna(value): return (f'

{label}

Not measured

' f'

{note}

') return (f'

{label}

' f'

{value * 100:.0f}/100

' f'
' f'

Higher than jobs held by {rank * 100:.0f}% of U.S. workers. {note}

') def verdict(r, fg, all_g): if pd.isna(r.g_post): return "BLS did not publish employment for this job in both 2022 and 2025, so its change can't be measured." ch = r.emp_2025 / r.emp_2022 - 1 field = MAJOR.get(r.major, "its field") s = (f"From May 2022 to May 2025, the number of people working as {e(r.title.lower())} " f"{'grew' if ch >= 0 else 'fell'} {pct(abs(ch), 1, sign=False)}. " f"Over the same years, {field.lower()} jobs {'grew' if fg >= 0 else 'fell'} {pct(abs(fg), 1, sign=False)} " f"and all jobs together {'grew' if all_g >= 0 else 'fell'} {pct(abs(all_g), 1, sign=False)}.") if not pd.isna(r.emp_2019): pre = r.emp_2022 / r.emp_2019 - 1 s += (f" Before ChatGPT existed (2019 to 2022) it had already " f"{'grown' if pre >= 0 else 'fallen'} {pct(abs(pre), 1, sign=False)}.") return s PAGE_HEAD = """ {title} {extra}
Overexposed
""" PAGE_FOOT = """ {scripts} """ def head(**kw): kw.setdefault("og_type", "article") kw.setdefault("og_title", kw["title"]) kw.setdefault("extra", "") kw.setdefault("jobs_cur", "") return PAGE_HEAD.format(base=BASE_URL, v=ASSET_V, **kw) def foot(scripts=""): return PAGE_FOOT.format(v=ASSET_V, scripts=scripts) def job_page(soc, r, df, tasks, fg, all_g, dists, n_study): if pd.isna(r.observed): not_in = " This job isn't one of them, because Anthropic's data has no AI use score for it." elif pd.isna(r.g_post): not_in = " This job isn't one of them, because BLS didn't publish its employment for both 2022 and 2025." else: not_in = "" t_all = tasks[tasks.soc == soc] used = t_all[t_all.penetration > 0].sort_values("penetration", ascending=False) wage_real = None if not pd.isna(r.wage_2025) and not pd.isna(r.wage_2022): wage_real = (r.wage_2025 / CPI[2025]) / (r.wage_2022 / CPI[2022]) - 1 field = MAJOR.get(r.major, "Other") b_rank = None if pd.isna(r.beta_gpt4) else weighted_pct_rank(*dists["beta"], r.beta_gpt4) o_rank = None if pd.isna(r.observed) else weighted_pct_rank(*dists["obs"], r.observed) density = 0.06 + 0.9 * min((0 if pd.isna(r.observed) else r.observed) / 0.75, 1) siblings = df[(df.index.str[:6] == soc[:6]) & (df.index != soc)] if len(siblings) < 3: siblings = df[(df.major == r.major) & (df.index != soc)].sort_values("emp_2025", ascending=False) sib_html = "".join(f'
  • {e(s.title)}
  • ' for _, s in siblings.head(8).iterrows()) task_rows = "".join( f'
  • {e(tr.task)}' f'{tr.penetration:.2f}
  • ' for tr in used.head(8).itertuples()) if not len(t_all): task_block = "

    O*NET lists no tasks for this job.

    " elif not len(used): task_block = (f"

    None of the {len(t_all)} tasks O*NET lists for this job showed up in " f"Anthropic's data on how people use Claude.

    ") else: task_block = (f"

    {len(used)} of the {len(t_all)} tasks O*NET lists for this job showed up in Anthropic's " f"data on how people use Claude. These have the highest scores " f"(0 means never seen, 1 is the highest).

      {task_rows}
    ") ch = None if pd.isna(r.g_post) else r.emp_2025 / r.emp_2022 - 1 obs_txt = "not measured" if pd.isna(r.observed) else f"{r.observed * 100:.0f}/100" desc = (f"{r.title}: {num(r.emp_2025)} U.S. workers in 2025, {pct(ch, 1)} since ChatGPT launched. " f"Observed AI exposure {obs_txt}. What the 2023 forecast said and what actually happened.") title = f"Will AI replace {r.title.lower()}? What the data shows · Overexposed" url = f"{BASE_URL}/jobs/{r.slug}/" ld = {"@context": "https://schema.org", "@type": "Occupation", "name": r.title, "occupationalCategory": soc, "description": "" if pd.isna(r.description) else r.description} if not pd.isna(r.wage_2025): ld["estimatedSalary"] = {"@type": "MonetaryAmountDistribution", "name": "base", "currency": "USD", "duration": "P1Y", "median": int(r.wage_2025)} extra = f'' years = [2019, 2020, 2021, 2022, 2023, 2024, 2025] body = f"""

    All jobs / {e(field)} / SOC {soc}

    {e(r.title)}

    {"" if pd.isna(r.description) else e(r.description)}

    What actually happened

    {verdict(r, fg, all_g)}

    A single job's numbers can't show that AI caused a change. Jobs rise and fall for many reasons. The study compares all {n_study} jobs at once to test that.{not_in}

    Workers, May of each year

    {sparkline(years, [r[f"emp_{y}"] for y in years])}

    Source: BLS Occupational Employment and Wage Statistics. BLS did not publish every job in every year.

    Workers, 2025
    {num(r.emp_2025)}
    Change since 2022
    {pct(ch, 1)}
    {e(field)} jobs, same years
    {pct(fg, 1)}
    Median pay, 2025
    {money(r.wage_2025)}
    Pay change since 2022, after inflation
    {pct(wage_real, 1)}
    {meter("The 2023 forecast", None if pd.isna(r.beta_gpt4) else r.beta_gpt4, b_rank, "Eloundou et al. rated each task: could an AI model make it at least twice as fast?")} {meter("Real AI use, 2025", None if pd.isna(r.observed) else r.observed, o_rank, "Anthropic's observed exposure: how much of this job's work people are actually doing with Claude.")}

    Where AI is already showing up

    {task_block}
    """ return head(title=e(title), desc=e(desc), url=url, og_title=e(f"Will AI replace {r.title.lower()}?"), extra=extra) + body + foot() def jobs_index(df, S): by_major = [] for mj, name in MAJOR.items(): s = df[df.major == mj].sort_values("title") if not len(s): continue items = "".join(f'
  • {e(r.title)}
  • ' for _, r in s.iterrows()) by_major.append(f'

    {e(name)} {len(s)}

    ') body = f"""

    Look up your job

    All {len(df)} jobs the government tracks, with what the 2023 AI forecast said about each one and what has actually happened since. The study itself uses {S["occupations_analyzed"]} of them; the other {S["occupations_without_data"]} are missing an AI use score or 2022 and 2025 job counts, and their pages say so.

    {"".join(by_major)}
    """ return (head(title="All jobs · Overexposed", desc=f"Look up any of {len(df)} U.S. jobs: what the 2023 AI forecast predicted and what actually happened to employment by 2025.", url=f"{BASE_URL}/jobs/", og_type="website", jobs_cur=' aria-current="page"') + body + foot(f'')) def fill_home(df, results): """The home page is hand-written HTML, but every number in its copy sits in an element tagged data-n="key". This rewrites those numbers from results.json, so copy and analysis can't drift apart.""" S, REG = results["summary"], results["regressions"] sgn = lambda v, d: (f"{v:+.{d}f}").replace("-", "−") per10 = lambda k: REG[k]["b"] / S["sd_observed"] * 10 # points of growth per 10 points of AI use groups = {g["group"]: g for g in results["use_groups"]} office = next(m for m in results["by_major"] if m["major"] == "43") t = results["tercile_index"]["beta_gpt4"] vals = { "use_high": sgn(groups["high"]["growth_post"] * 100, 1) + "%", "use_none": sgn(groups["none"]["growth_post"] * 100, 1) + "%", "slope_raw": sgn(per10("g_post|observed|raw"), 1), "slope_raw_abs": f"{abs(per10('g_post|observed|raw')):.1f}", "slope_fe": sgn(per10("g_post|observed|major_fe"), 1), "p_fe": f"{REG['g_post|observed|major_fe']['p']:.2f}", "office_pre": f"{abs(office['growth_pre']) * 100:.1f}%", "office_post": f"{abs(office['growth_post']) * 100:.1f}%", "terc_pre_top": sgn((100 / t["top"][0] - 1) * 100, 1) + "%", "terc_pre_bot": sgn((100 / t["bottom"][0] - 1) * 100, 1) + "%", "terc_post_top": sgn(t["top"][-1] - 100, 1) + "%", "terc_post_bot": sgn(t["bottom"][-1] - 100, 1) + "%", "p_race": f"{results['horse_race']['raw']['z_beta_gpt4']['p']:.2f}", } for soc in ["43-9021", "43-4051", "15-1251", "15-2051", "13-2051"]: r = df.loc[soc] vals[f"post_{soc}"] = sgn((r.emp_2025 / r.emp_2022 - 1) * 100, 0) + "%" if not pd.isna(r.emp_2019): vals[f"pre_{soc}"] = sgn((r.emp_2022 / r.emp_2019 - 1) * 100, 0) + "%" path = SITE / "index.html" page = path.read_text() for k, v in vals.items(): page, n = re.subn(rf'(data-n="{re.escape(k)}"[^>]*>)[^<]*(<)', rf"\g<1>{v}\g<2>", page) assert n >= 1, f"home page has no data-n={k}" left = set(re.findall(r'data-n="([^"]+)"', page)) - set(vals) assert not left, f"home page numbers with no source: {left}" path.write_text(page) return vals def main(): df, tasks, results = load() (SITE / "data").mkdir(parents=True, exist_ok=True) (SITE / "data" / "story.json").write_text(json.dumps(story_data(df), separators=(",", ":"))) (SITE / "data" / "search.json").write_text(json.dumps(search_data(df), separators=(",", ":"))) keep = {k: results[k] for k in ["summary", "horse_race", "event_study", "quintiles", "use_groups", "tercile_index", "by_major", "poster_children"]} keep["reg"] = {k: v for k, v in results["regressions"].items() if k.split("|")[1] in ("observed", "beta_gpt4")} (SITE / "data" / "results.json").write_text(json.dumps(keep, separators=(",", ":"))) fg, all_g = field_growth(df) w = df.emp_2025.fillna(0).to_numpy() dists = {"beta": (df.beta_gpt4.to_numpy(), w), "obs": (df.observed.to_numpy(), w)} for soc, r in df.iterrows(): out = SITE / "jobs" / r.slug out.mkdir(parents=True, exist_ok=True) (out / "index.html").write_text(job_page(soc, r, df, tasks, fg.get(r.major, np.nan), all_g, dists, results["summary"]["occupations_analyzed"])) (SITE / "jobs" / "index.html").write_text(jobs_index(df, results["summary"])) urls = ["/", "/jobs/", "/paper/", "/credits/"] + [f"/jobs/{s}/" for s in df.slug] (SITE / "sitemap.xml").write_text( '\n\n' + "".join(f" {BASE_URL}{u}\n" for u in urls) + "\n") print("home page numbers:", fill_home(df, results)) print(f"wrote {len(df)} job pages, story rows: {len(story_data(df)['rows'])}") if __name__ == "__main__": main()