us-largest-layoffs-events-warn-act / hf_largest_events.py
APProjects's picture
daily largest-events refresh
0f72821 verified
Raw
History Blame
25 kB
#!/usr/bin/env python3
"""Publish the LARGEST US LAYOFF EVENTS (WARN Act, 1988-present) as its own HF
dataset. (c334, 2026-09-12 — board c333 repair item R2.)
WHY THIS EXISTS — the evidence, not a hunch:
* Standing rule from c319: a new HF dataset must be a COMPUTED CUT that owns a
query no existing artifact answers — never "the same rows, filtered".
* Checked on the Hub 2026-09-12 BEFORE publishing: `largest layoffs`,
`biggest layoffs` and `layoff events` each returned **0 datasets** hub-wide
(`mass layoffs` returned only our own closings-vs-layoffs set). Re-verify:
curl -s "https://huggingface.co/api/datasets?search=largest+layoffs"
* Why it cannot be copied from a portal scrape: a state portal lists one row
per SITE per NOTICE. "The largest layoff" is an EMPLOYER-level fact that
only exists after (1) 48 portals are in one schema, (2) the employer's 22
spellings are resolved to one group (alias_merge.py — the c309 join that is
this venture's actual moat), and (3) the rolling per-site notices are
clustered into one event. None of those three steps is on any portal.
WHAT AN "EVENT" IS (say it on the card, keep it in the columns):
* One employer GROUP (alias-merged), its notices sorted by date, split into
events wherever the gap between consecutive notice dates exceeds
EVENT_GAP_DAYS. A rolling programme (Boeing filed monthly Jun-Nov 2020) is
ONE event; the same employer's 2023 cuts are a separate event.
* `workers_reported` sums `employees_affected` over the event's notices AFTER
dropping exact duplicate rows (same state + location + count + notice date +
effective date — some portals list the same site twice). Successive notices for the
same site are NOT collapsed: we cannot tell from a portal whether a second
notice is cumulative or incremental, so the sum can overstate a rolling
programme. `sites` (distinct state+location) is the conservative companion.
HONESTY RAILS (read before editing):
1. Every event carries its `notice_ids` so any row can be re-derived from the
free flagship CSV; nothing here is hand-typed.
2. `single_notice=true` flags events built from ONE filing — those are only as
good as the one portal row (e.g. a 16,132-worker staffing-firm closure).
3. `states_covered_in_year` says how many states the archive holds any notice
for in the event's year. Pre-2020 the archive is thin (IL/OR go back to
1988; most states start 2010-2023), so an early-year ranking is a ranking
of the states we hold, not of the country. The card says so first.
4. The current year is a running total; events that started in the last
EVENT_GAP_DAYS days may still grow (`event_open=true`).
5. Every number is recounted from out/full/warn_notices.csv on every run; the
card, the chart and the CSV are written from ONE in-memory result.
Reads : out/full/warn_notices.csv (this build), out/employer_slugs.json
Writes: out/largest_events.csv, repo/data/largest_layoff_events.csv,
hf_largest_events_staging/ then uploads to <user>/DATASET_NAME
Usage (cwd = product/):
python3 hf_largest_events.py --selftest
HF_STAGE_ONLY=1 python3 hf_largest_events.py
.venv-hf/bin/python3 hf_largest_events.py
Env: HF_TOKEN. Non-fatal by convention in publish.sh.
"""
import collections
import csv
import datetime
import json
import os
import re
import shutil
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import alias_merge # noqa: E402
import dataviz # noqa: E402
DATASET_NAME = "us-largest-layoffs-events-warn-act" # "layoffs" plural on purpose: Hub search is substring-per-token on the id (c334)
STAGE = "hf_largest_events_staging"
NOTICES = os.path.join(HERE, "out", "full", "warn_notices.csv")
SLUGS = os.path.join(HERE, "out", "employer_slugs.json")
OUT_CSV = os.path.join(HERE, "out", "largest_events.csv")
REPO_CSV = os.path.join(HERE, "repo", "data", "largest_layoff_events.csv")
SITE = "https://approjects-warn-act-notices.static.hf.space"
REPO = "https://github.com/APVentureEngine/warn-act-notices"
NOTICE_DS = "https://huggingface.co/datasets/APProjects/us-warn-act-layoffs-notices-daily"
MULTI_DS = "https://huggingface.co/datasets/APProjects/us-multi-state-layoffs-employers-warn-act"
RATES_DS = "https://huggingface.co/datasets/APProjects/us-layoffs-per-capita-by-state-warn-act"
WATCH = "https://approj.gumroad.com/l/warn-watch"
FREE_WATCH = "https://approj.gumroad.com/l/warn-free-watch"
EVENT_GAP_DAYS = 45 # a gap longer than this between an employer's notices starts a new event
MAX_EVENT_DAYS = 183 # ...and an event never spans more than ~6 months (Boeing files in WA every
# few weeks for years; without this cap 2014-2018 chained into one "event")
TOP_N = 1000 # rows published
MIN_EVENTS = 200 # refuse to publish a table thinner than this
MIN_WORKERS = 1 # an event with no reported worker count cannot be ranked by workers
COLS = ["rank", "employer", "event_start", "event_end", "year", "workers_reported", "notices",
"notices_with_worker_count", "sites", "states", "states_count", "largest_single_notice",
"largest_notice_state", "largest_notice_location", "notice_types", "single_notice",
"event_open", "duplicates_dropped", "states_covered_in_year", "employer_page", "notice_ids"]
def _date(r):
d = (r.get("notice_date") or r.get("effective_date") or "")[:10]
try:
return datetime.date.fromisoformat(d)
except ValueError:
return None
def _int(v):
try:
n = int(float(str(v).replace(",", "")))
except (TypeError, ValueError):
return None
return n if n > 0 else None
def _loc(r):
return re.sub(r"\s+", " ", (r.get("location") or "").strip().lower())
def _display(rows_in_group, key, key_names):
"""The group key's own spelling as it appears anywhere in the archive (so a 2020 event of
14 Hyatt Regency hotels reads 'Hyatt Regency', not 'Hyatt Regency - Portland'); otherwise
the most frequent spelling inside the event, shortest on ties."""
if key in key_names:
return key_names[key]
c = collections.Counter((r.get("company_canonical") or r.get("company") or "").strip()
for r in rows_in_group)
return sorted(c.items(), key=lambda kv: (-kv[1], len(kv[0]), kv[0]))[0][0]
def build(rows=None, today=None, slugs=None, gap_days=EVENT_GAP_DAYS, top_n=TOP_N):
rows = rows if rows is not None else list(csv.DictReader(open(NOTICES, encoding="utf-8")))
today = today or datetime.date.today()
if slugs is None:
try:
slugs = json.load(open(SLUGS, encoding="utf-8"))
except (OSError, ValueError):
slugs = {}
amap = alias_merge.build_alias_map(rows)
groups = collections.defaultdict(list)
covered = collections.defaultdict(set)
spell = collections.defaultdict(collections.Counter) # lowercased canonical -> raw spellings
for r in rows:
c = alias_merge.canon_of(r)
raw = (r.get("company_canonical") or r.get("company") or "").strip()
if c and raw:
spell[c][raw] += 1
key_names = {k: sorted(v.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] for k, v in spell.items()}
for r in rows:
d = _date(r)
if d is None or d > today + datetime.timedelta(days=730):
continue
st = (r.get("state") or "").upper()
covered[d.year].add(st)
c = alias_merge.canon_of(r)
if not c:
continue
groups[amap.get(c, c)].append((d, r))
gap = datetime.timedelta(days=gap_days)
events = []
for key, items in groups.items():
items.sort(key=lambda t: t[0])
cur = []
for d, r in items:
if cur and ((d - cur[-1][0]) > gap or (d - cur[0][0]).days > MAX_EVENT_DAYS):
events.append((key, cur))
cur = []
cur.append((d, r))
if cur:
events.append((key, cur))
out = []
for key, ev in events:
seen, kept, dups = set(), [], 0
for d, r in ev:
sig = ((r.get("state") or "").upper(), _loc(r), _int(r.get("employees_affected")),
(r.get("notice_date") or "")[:10], (r.get("effective_date") or "")[:10])
if sig in seen:
dups += 1
continue
seen.add(sig)
kept.append((d, r))
counts = [(_int(r.get("employees_affected")) or 0, r) for _, r in kept]
workers = sum(n for n, _ in counts)
if workers < MIN_WORKERS:
continue
big_n, big_r = max(counts, key=lambda t: t[0])
states = sorted({(r.get("state") or "").upper() for _, r in kept if r.get("state")})
types = sorted({(r.get("notice_type") or "").strip() for _, r in kept} - {""})
start, end = kept[0][0], kept[-1][0]
out.append({
"rank": 0,
"employer": _display([r for _, r in kept], key, key_names),
"event_start": start.isoformat(), "event_end": end.isoformat(), "year": start.year,
"workers_reported": workers, "notices": len(kept),
"notices_with_worker_count": sum(1 for n, _ in counts if n),
"sites": len({((r.get("state") or "").upper(), _loc(r)) for _, r in kept}),
"states": ";".join(states), "states_count": len(states),
"largest_single_notice": big_n,
"largest_notice_state": (big_r.get("state") or "").upper(),
"largest_notice_location": (big_r.get("location") or "").strip(),
"notice_types": ";".join(types)[:200],
"single_notice": "true" if len(kept) == 1 else "false",
"event_open": "true" if (today - end) <= gap else "false",
"duplicates_dropped": dups,
"states_covered_in_year": len(covered.get(start.year, ())),
"employer_page": (SITE + "/" + slugs[key]) if key in slugs else "",
"notice_ids": ";".join(r.get("id") or "" for _, r in kept),
})
out.sort(key=lambda e: (-e["workers_reported"], e["event_start"], e["employer"]))
out = out[:top_n]
for i, e in enumerate(out, 1):
e["rank"] = i
stats = {
"events_total": len(events), "rows": len(out),
"workers_in_table": sum(e["workers_reported"] for e in out),
"notices_in_table": sum(e["notices"] for e in out),
"multi_notice_rows": sum(1 for e in out if e["single_notice"] == "false"),
"multi_state_rows": sum(1 for e in out if e["states_count"] > 1),
"dups_dropped": sum(e["duplicates_dropped"] for e in out),
"years": sorted({e["year"] for e in out}),
"asof": today.isoformat(), "cur_year": today.year, "gap_days": gap_days,
"states_covered_now": len(covered.get(today.year, ())),
"min_workers_in_table": out[-1]["workers_reported"] if out else 0,
}
return {"rows": out, "stats": stats}
CARD = """---
pretty_name: Largest US layoff events since 1988 - WARN Act notices clustered by employer
license: cc-by-4.0
language:
- en
task_categories:
- tabular-classification
tags:
- layoffs
- largest-layoffs
- biggest-layoffs
- layoff-events
- mass-layoffs
- warn-act
- warn-notices
- entity-resolution
- labor-market
- corporate-events
- public-records
- government-data
- alternative-data
- united-states
- daily-updated
- tabular
size_categories:
- 1K<n<10K
configs:
- config_name: default
data_files:
- split: train
path: data/largest_layoff_events.csv
---
# The {rows:,} largest US layoff events on record under the WARN Act, {y0}-{y1}
**Rebuilt {asof}. Largest on file: {top_employer}, {top_start} to {top_end} — {top_workers:,}
workers across {top_notices} notices in {top_states} state(s). The table's floor is
{min_workers:,} workers; {multi_notice:,} of the {rows:,} events span more than one notice and
{multi_state:,} span more than one state.**
A state WARN portal lists one row per site per notice. "What was the biggest layoff?" is an
employer-level question, and answering it takes three steps no portal performs: 48 agencies'
notices normalized into one schema daily, an employer's many spellings resolved to one name
(Boeing files under 22 of them, typos included), and its rolling per-site notices clustered into
one event. This dataset is the result, top {rows:,} by reported workers, rebuilt daily.
![Largest layoff events by reported workers](chart.svg)
## Read this before quoting a rank
* **Coverage is uneven before ~2020.** The archive reaches back to 1988 only for the states
whose portals kept history (Illinois and Oregon among them); most states begin between 2010
and 2023. `states_covered_in_year` says how many states the archive holds for the event's
year — an early-year rank is a rank among the states we hold, not the country.
* **An event is one employer's notices with no gap longer than {gap} days between consecutive
notice dates, and no longer than {maxdays} days end to end.** A rolling programme is one event;
a later round, or the seventh month of a continuous programme, is a separate event.
* **`workers_reported` can overstate a rolling programme.** Exact duplicate rows (same state,
location, count, notice date and effective date) are dropped (`duplicates_dropped`), but successive
notices for the same site are summed because a portal does not say whether the second is
cumulative. `sites` is the conservative companion figure.
* **`single_notice=true` means the whole event is one portal row.** It is only as reliable as
that row; check it at the source before repeating it.
* Employer names are resolved by [`alias_merge.py`]({repo}/blob/main/product/alias_merge.py)
(token signature + purity-guarded prefix absorption); the resolver ships in this repo. It
merges spellings, not corporate parents: subsidiaries filing under their own names are their
own employers.
* The current year is a running total; `event_open=true` marks events that may still grow.
## Top 20 right now
| # | employer | period | workers | notices | states |
|---|---|---|---|---|---|
{top20}
## Columns
| column | meaning |
|---|---|
| `rank` | position by `workers_reported` (ties: earlier start first) |
| `employer` | most frequent canonical spelling inside the event |
| `event_start`, `event_end`, `year` | first and last notice date; `year` is the start year |
| `workers_reported` | sum of `employees_affected` over the event's de-duplicated notices |
| `notices`, `notices_with_worker_count` | notices in the event; how many carried a count |
| `sites` | distinct state + location pairs |
| `states`, `states_count` | semicolon-separated state codes |
| `largest_single_notice`, `largest_notice_state`, `largest_notice_location` | the biggest single filing inside the event |
| `notice_types` | distinct raw `notice_type` strings, as the portals wrote them |
| `single_notice` | `true` when the event is a single filing |
| `event_open` | `true` when the last notice is within {gap} days of the rebuild date |
| `duplicates_dropped` | exact duplicate portal rows removed before summing |
| `states_covered_in_year` | states with any notice in the archive for `year` |
| `employer_page` | the employer's history page on the site, when one exists |
| `notice_ids` | semicolon-separated ids joining to the flagship notices CSV |
## Where the rows come from
The free, CC BY 4.0 [normalized WARN archive]({notice_ds}) rebuilt daily from 48 state portals
([site]({site}), [GitHub]({repo})). Related cuts of the same archive: [employers filing in
several states]({multi_ds}) and [layoffs per capita by state]({rates_ds}).
Get told the day an employer on your list files, in any of the 48 states: [free 30-day
watch]({free_watch}) (no card) or [WARN Watch, $49/year]({watch}) for a list of up to 500
employers.
*Automated publisher (APProjects). Not affiliated with any government agency. Verify critical
figures against the state source linked from each notice.*
"""
def render(res):
rows, st = res["rows"], res["stats"]
if st["rows"] < MIN_EVENTS:
raise SystemExit(f"hf_largest_events: only {st['rows']} events; refusing to render")
top = rows[0]
top20 = "\n".join(
f"| {e['rank']} | {e['employer']} | {e['event_start']} to {e['event_end']} | "
f"{e['workers_reported']:,} | {e['notices']} | {e['states']} |"
for e in rows[:20])
svg = dataviz.bar_chart([(f"{e['employer'][:28]} ({e['year']})", e["workers_reported"])
for e in rows[:15]], unit=" workers")
card = CARD.format(
rows=st["rows"], y0=min(st["years"]), y1=max(st["years"]), asof=st["asof"],
top_employer=top["employer"], top_start=top["event_start"], top_end=top["event_end"],
top_workers=top["workers_reported"], top_notices=top["notices"],
top_states=top["states_count"], min_workers=st["min_workers_in_table"],
multi_notice=st["multi_notice_rows"], multi_state=st["multi_state_rows"],
gap=st["gap_days"], maxdays=MAX_EVENT_DAYS, top20=top20, repo=REPO, notice_ds=NOTICE_DS, site=SITE,
multi_ds=MULTI_DS, rates_ds=RATES_DS, free_watch=FREE_WATCH, watch=WATCH,
)
return card, svg
README_ANCHOR = "<!--largest-events-readme-->"
README_PATH = os.path.join(HERE, "repo", "README.md")
HF_URL = f"https://huggingface.co/datasets/APProjects/{DATASET_NAME}"
def inject_readme(res, readme_path=README_PATH):
"""One idempotent README line under the per-capita line (GitHub = the human channel)."""
st = res["stats"]
if not res["rows"]:
return False
top = res["rows"][0]
line = (f"{README_ANCHOR} \U0001F3ED **[The {st['rows']:,} largest US layoff events since "
f"{min(st['years'])}](data/largest_layoff_events.csv)** — notices clustered per resolved "
f"employer (rolling programmes = one event); #1 {top['employer']} {top['year']}, "
f"{top['workers_reported']:,} workers over {top['notices']} notices. "
f"[Card on Hugging Face]({HF_URL}).")
txt = open(readme_path, encoding="utf-8").read()
txt = "\n".join(ln for ln in txt.split("\n") if README_ANCHOR not in ln)
for key in ("<!--state-rates-readme-->", "<!--metro-readme-->", "<!--county-readme-->"):
i = txt.find(key)
if i >= 0:
j = txt.find("\n", i)
txt = txt[:j + 1] + line + "\n" + txt[j + 1:]
break
else:
k = txt.find("\n## ")
txt = (txt[:k] + "\n\n" + line + "\n" + txt[k:]) if k >= 0 else txt + "\n\n" + line + "\n"
assert txt.count(README_ANCHOR) == 1
open(readme_path, "w", encoding="utf-8").write(txt)
print("hf_largest_events: README line injected")
return True
def write_csv(path, rows):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=COLS)
w.writeheader()
w.writerows(rows)
def stage(res):
card, svg = render(res)
root = os.path.join(HERE, STAGE)
shutil.rmtree(root, ignore_errors=True)
os.makedirs(os.path.join(root, "data"), exist_ok=True)
open(os.path.join(root, "README.md"), "w", encoding="utf-8").write(card)
open(os.path.join(root, "chart.svg"), "w", encoding="utf-8").write(svg)
write_csv(os.path.join(root, "data", "largest_layoff_events.csv"), res["rows"])
for fn in ("hf_largest_events.py", "alias_merge.py", "dataviz.py"):
shutil.copy2(os.path.join(HERE, fn), os.path.join(root, fn))
print(f"hf_largest_events: staged {res['stats']['rows']} events "
f"(of {res['stats']['events_total']}) -> {STAGE}/")
return root
def upload():
token = os.environ.get("HF_TOKEN")
if not token:
print("HF_TOKEN not set - staged only, nothing uploaded.")
return 0
from huggingface_hub import HfApi
api = HfApi(token=token)
user = api.whoami()["name"]
repo_id = f"{user}/{DATASET_NAME}"
api.create_repo(repo_id, repo_type="dataset", exist_ok=True)
api.upload_folder(folder_path=os.path.join(HERE, STAGE), repo_id=repo_id,
repo_type="dataset", commit_message="daily largest-events refresh")
print(f"uploaded -> https://huggingface.co/datasets/{repo_id}")
return 0
def selftest():
def n(i, st, comp, wc, nd, loc="Plant", ed="", nt="Layoff"):
return {"id": f"id{i}", "state": st, "company": comp, "company_canonical": comp,
"employees_affected": wc, "notice_date": nd, "effective_date": ed,
"location": loc, "notice_type": nt}
rows = [
# Boeing: 3 notices within 45d = one event, plus one 200 days later = second event
n(1, "WA", "Boeing", "500", "2020-06-01"),
n(2, "WA", "Boeing", "300", "2020-07-01"), # (parent needs >= 3 exact rows)
n(3, "CA", "Boeing - El Paso", "50", "2020-08-10", loc="El Paso"), # alias-merged spelling
n(4, "WA", "Boeing", "100", "2021-03-01"),
# Rolling filer: 8 notices 30 days apart = 210 days -> must split at the 183-day cap
*[n(20 + i, "KS", "Roller", "10", (datetime.date(2019, 1, 1) + datetime.timedelta(days=30 * i)).isoformat())
for i in range(8)],
# exact duplicate portal row must be dropped, not summed
n(5, "TX", "Acme", "400", "2022-01-05", ed="2022-03-01"),
n(6, "TX", "Acme", "400", "2022-01-05", ed="2022-03-01"),
# single notice giant; no worker count row must not rank
n(7, "NJ", "Giant Staffing", "9000", "2025-05-20"),
n(8, "NJ", "Ghost", "", "2025-05-20"),
n(9, "NJ", "Bad Date", "10", "not-a-date"),
]
today = datetime.date(2026, 9, 12)
res = build(rows, today=today, slugs={"boeing": "employers/b/boeing.html"}, top_n=20)
by = {(e["employer"], e["event_start"]): e for e in res["rows"]}
b1 = by[("Boeing", "2020-06-01")]
assert b1["workers_reported"] == 850 and b1["notices"] == 3 and b1["states"] == "CA;WA", b1
assert b1["sites"] == 2 and b1["largest_single_notice"] == 500 and b1["largest_notice_state"] == "WA"
assert b1["employer_page"].endswith("employers/b/boeing.html")
assert ("Boeing", "2021-03-01") in by, "second round must be a separate event"
acme = by[("Acme", "2022-01-05")]
assert acme["workers_reported"] == 400 and acme["duplicates_dropped"] == 1 and acme["notices"] == 1
g = by[("Giant Staffing", "2025-05-20")]
assert g["single_notice"] == "true" and res["rows"][0] is g
assert not any(e["employer"] in ("Ghost", "Bad Date") for e in res["rows"])
assert all(e["event_open"] == "false" for e in res["rows"])
assert b1["states_covered_in_year"] == 2 and [e["rank"] for e in res["rows"]] == list(range(1, 7))
assert b1["notice_ids"] == "id1;id2;id3"
roll = [e for e in res["rows"] if e["employer"] == "Roller"]
assert len(roll) == 2 and sorted(e["notices"] for e in roll) == [1, 7], roll
# render must refuse a thin table, and must not leave placeholders when it renders
try:
render(res)
except SystemExit:
pass
else:
raise AssertionError("render must refuse < MIN_EVENTS events")
wide = [n(100 + i, "IL", f"Employer {i}", str(10 + i), f"2024-01-{1 + i % 28:02d}")
for i in range(MIN_EVENTS + 5)]
wide.append(n(999, "IL", "Employer 3", "5", "2026-09-01")) # open event in the current year
res2 = build(wide, today=today, slugs={}, top_n=TOP_N)
assert any(e["event_open"] == "true" for e in res2["rows"])
card, svg = render(res2)
left = re.findall(r"\{[a-z_0-9]+\}", card)
assert not left, f"unformatted placeholder: {left}"
assert "<svg" in svg and "| 1 | Employer" in card and "45 days" in card
import tempfile
tmp = tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8")
tmp.write("# T\n\n<!--metro-readme--> metro line\n<!--state-rates-readme--> rates line\n\n## Next\n")
tmp.close()
inject_readme(res2, tmp.name); inject_readme(res2, tmp.name)
t = open(tmp.name, encoding="utf-8").read()
assert t.count(README_ANCHOR) == 1 and t.index("rates line") < t.index(README_ANCHOR)
os.unlink(tmp.name)
print(f"hf_largest_events selftest: ok ({len(res['rows'])} events in fixture, card {len(card)} chars)")
return 0
def main():
if "--selftest" in sys.argv:
return selftest()
res = build()
write_csv(OUT_CSV, res["rows"])
write_csv(REPO_CSV, res["rows"])
try:
inject_readme(res)
except Exception as e: # noqa: BLE001 — a README line must never block the upload
print(f"hf_largest_events: WARN README injection failed ({e})")
stage(res)
if os.environ.get("HF_STAGE_ONLY"):
print("HF_STAGE_ONLY set - not uploading.")
return 0
return upload()
if __name__ == "__main__":
sys.exit(main())