Initial commit

This commit is contained in:
ebagot committed 2026-11-13 17:35:10 +01:00
commit a206bfb5db
21 files changed
+16747

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
data/
**/__pycache__/
*.pyc
+20
View File
@@ -0,0 +1,20 @@
FROM python:3.12-slim
WORKDIR /app
# d3 and topojson are copied into the image so the page does not need a CDN at runtime
# (checksums pinned to the files downloaded when this project was set up).
ADD --checksum=sha256:f2094bbf6141b359722c4fe454eb6c4b0f0e42cc10cc7af921fc158fceb86539 https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js static/vendor/d3.min.js
ADD --checksum=sha256:b47a003c6a0d761211dbc60797d0d62f37917ddc228241fb38205732b1d78683 https://cdnjs.cloudflare.com/ajax/libs/topojson/3.0.2/topojson.min.js static/vendor/topojson.min.js
RUN chmod 644 static/vendor/*.js
COPY app/ /app/
ENV DATA_DIR=/data \
PORT=8080 \
UPDATE_MODE=auto \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
EXPOSE 8080
CMD ["python", "server.py"]
+64
View File
@@ -0,0 +1,64 @@
# Carte des élus américains
Carte interactive des États-Unis : sénateurs et représentants fédéraux, gouverneur et chambres législatives de chaque État, avec un bouton qui relit Wikipédia (en anglais) pour rafraîchir les données. Python 3.12 seul, sans dépendance.
## Lancer
```sh
docker compose up -d --build
```
Puis ouvrir <http://localhost:8080>. Au premier démarrage, le dossier `./data` est rempli avec les données de départ (lues sur Wikipédia le 13 novembre 2026).
Le port n'est ouvert que sur la machine locale (`127.0.0.1:8080`). Pour l'ouvrir au réseau, remplacer la ligne `ports` de `docker-compose.yml` par `"8080:8080"`.
Arrêter : `docker compose down` (les données restent dans `./data`).
## Mettre à jour les données
- **Depuis la page** : bouton « Update from Wikipedia ». La progression s'affiche, puis la carte se recharge. Les avertissements sont listés sous le bouton.
- **En ligne de commande** :
```sh
docker compose run --rm app python update.py
```
Une seule mise à jour à la fois (le bouton refuse une seconde demande, la ligne de commande aussi). Une mise à jour fait une dizaine de requêtes à Wikipédia et dure moins d'une minute.
## Choisir le mode
`UPDATE_MODE` vaut `auto` (par défaut), `election` ou `current` :
- `election` : résultats de la dernière élection (pages « 2026 United States … elections »), soit les élus qui siégeront à partir de janvier.
- `current` : élus en fonction aujourd'hui (listes « List of current … » et article de chaque chambre).
- `auto` : `election` entre le jour de l'élection (novembre des années paires) et le 3 janvier suivant, `current` le reste du temps.
Forcer le mode :
```sh
# ligne de commande
docker compose run --rm -e UPDATE_MODE=current app python update.py
# bouton de la page : mettre UPDATE_MODE=current dans un fichier .env à côté de docker-compose.yml, puis
docker compose up -d
```
## Où sont les données
Dans `./data` (monté dans le conteneur sur `/data`) :
- `senate.json`, `house.json`, `governors.json`, `legislatures.json` : une catégorie par fichier, avec la date de lecture, le mode et les pages Wikipédia utilisées ;
- `meta.json` : le dernier passage (date, mode, avertissements).
Chaque catégorie est vérifiée avant de remplacer l'ancien fichier (50 États, 100 sénateurs, 435 représentants selon la répartition par État, 50 gouverneurs, 99 chambres dont les sièges font le bon total). Si la lecture ou la vérification échoue, l'ancienne version est gardée et un avertissement l'explique. Les fichiers sont écrits d'un coup (fichier temporaire puis renommage).
Les pouvoirs des gouverneurs ne sont pas lus sur Wikipédia : ils viennent des données de départ (`app/seed/governors.json`).
Pour revenir aux données de départ : `docker compose down`, vider `./data`, puis `docker compose up -d`.
## Limites connues
- La lecture dépend de la mise en page des articles Wikipédia : si un tableau change de forme, la catégorie concernée garde ses anciennes données et un avertissement le signale.
- En mode `election`, une chambre dont Wikipédia n'a pas encore publié les résultats garde les chiffres déjà connus pour la même élection ; sinon tous ses sièges sont comptés « Not yet called ».
- Une course non tranchée n'affiche pas de gagnant, seulement les deux principaux candidats.
- Les présidents de chambre affichés sont ceux en fonction ; la fin de leur mandat est déduite de la prochaine élection de la chambre (indiqué dans la note).
+243
View File
@@ -0,0 +1,243 @@
"""Shared constants, date rules and file storage for the officeholders map."""
import datetime as dt
import json
import os
import shutil
import tempfile
APP_DIR = os.path.dirname(os.path.abspath(__file__))
SEED_DIR = os.path.join(APP_DIR, "seed")
DATA_DIR = os.environ.get("DATA_DIR", os.path.join(APP_DIR, "..", "data"))
CATEGORIES = ["senate", "house", "governors", "legislatures"]
STATES = {
"Alabama": "AL", "Alaska": "AK", "Arizona": "AZ", "Arkansas": "AR", "California": "CA",
"Colorado": "CO", "Connecticut": "CT", "Delaware": "DE", "Florida": "FL", "Georgia": "GA",
"Hawaii": "HI", "Idaho": "ID", "Illinois": "IL", "Indiana": "IN", "Iowa": "IA",
"Kansas": "KS", "Kentucky": "KY", "Louisiana": "LA", "Maine": "ME", "Maryland": "MD",
"Massachusetts": "MA", "Michigan": "MI", "Minnesota": "MN", "Mississippi": "MS", "Missouri": "MO",
"Montana": "MT", "Nebraska": "NE", "Nevada": "NV", "New Hampshire": "NH", "New Jersey": "NJ",
"New Mexico": "NM", "New York": "NY", "North Carolina": "NC", "North Dakota": "ND", "Ohio": "OH",
"Oklahoma": "OK", "Oregon": "OR", "Pennsylvania": "PA", "Rhode Island": "RI", "South Carolina": "SC",
"South Dakota": "SD", "Tennessee": "TN", "Texas": "TX", "Utah": "UT", "Vermont": "VT",
"Virginia": "VA", "Washington": "WA", "West Virginia": "WV", "Wisconsin": "WI", "Wyoming": "WY",
}
NAMES = {code: name for name, code in STATES.items()}
# U.S. House seats per state (apportionment after the 2020 census, in force until the 2032 election).
APPORTIONMENT = {
"AL": 7, "AK": 1, "AZ": 9, "AR": 4, "CA": 52, "CO": 8, "CT": 5, "DE": 1, "FL": 28, "GA": 14,
"HI": 2, "ID": 2, "IL": 17, "IN": 9, "IA": 4, "KS": 4, "KY": 6, "LA": 6, "ME": 2, "MD": 8,
"MA": 9, "MI": 13, "MN": 8, "MS": 4, "MO": 8, "MT": 2, "NE": 3, "NV": 4, "NH": 2, "NJ": 12,
"NM": 3, "NY": 26, "NC": 14, "ND": 1, "OH": 15, "OK": 5, "OR": 6, "PA": 17, "RI": 2, "SC": 7,
"SD": 1, "TN": 9, "TX": 38, "UT": 4, "VT": 1, "VA": 11, "WA": 10, "WV": 2, "WI": 8, "WY": 1,
}
# State chambers: Wikipedia article title and size. Nebraska is unicameral (stored as "upper").
CHAMBERS = {
"AL": (("Alabama Senate", 35), ("Alabama House of Representatives", 105)),
"AK": (("Alaska Senate", 20), ("Alaska House of Representatives", 40)),
"AZ": (("Arizona Senate", 30), ("Arizona House of Representatives", 60)),
"AR": (("Arkansas Senate", 35), ("Arkansas House of Representatives", 100)),
"CA": (("California State Senate", 40), ("California State Assembly", 80)),
"CO": (("Colorado Senate", 35), ("Colorado House of Representatives", 65)),
"CT": (("Connecticut State Senate", 36), ("Connecticut House of Representatives", 151)),
"DE": (("Delaware Senate", 21), ("Delaware House of Representatives", 41)),
"FL": (("Florida Senate", 40), ("Florida House of Representatives", 120)),
"GA": (("Georgia State Senate", 56), ("Georgia House of Representatives", 180)),
"HI": (("Hawaii Senate", 25), ("Hawaii House of Representatives", 51)),
"ID": (("Idaho Senate", 35), ("Idaho House of Representatives", 70)),
"IL": (("Illinois Senate", 59), ("Illinois House of Representatives", 118)),
"IN": (("Indiana Senate", 50), ("Indiana House of Representatives", 100)),
"IA": (("Iowa Senate", 50), ("Iowa House of Representatives", 100)),
"KS": (("Kansas Senate", 40), ("Kansas House of Representatives", 125)),
"KY": (("Kentucky Senate", 38), ("Kentucky House of Representatives", 100)),
"LA": (("Louisiana State Senate", 39), ("Louisiana House of Representatives", 105)),
"ME": (("Maine Senate", 35), ("Maine House of Representatives", 151)),
"MD": (("Maryland Senate", 47), ("Maryland House of Delegates", 141)),
"MA": (("Massachusetts Senate", 40), ("Massachusetts House of Representatives", 160)),
"MI": (("Michigan Senate", 38), ("Michigan House of Representatives", 110)),
"MN": (("Minnesota Senate", 67), ("Minnesota House of Representatives", 134)),
"MS": (("Mississippi State Senate", 52), ("Mississippi House of Representatives", 122)),
"MO": (("Missouri Senate", 34), ("Missouri House of Representatives", 163)),
"MT": (("Montana Senate", 50), ("Montana House of Representatives", 100)),
"NE": (("Nebraska Legislature", 49), None),
"NV": (("Nevada Senate", 21), ("Nevada State Assembly", 42)),
"NH": (("New Hampshire Senate", 24), ("New Hampshire House of Representatives", 400)),
"NJ": (("New Jersey Senate", 40), ("New Jersey General Assembly", 80)),
"NM": (("New Mexico Senate", 42), ("New Mexico House of Representatives", 70)),
"NY": (("New York State Senate", 63), ("New York State Assembly", 150)),
"NC": (("North Carolina Senate", 50), ("North Carolina House of Representatives", 120)),
"ND": (("North Dakota Senate", 47), ("North Dakota House of Representatives", 94)),
"OH": (("Ohio Senate", 33), ("Ohio House of Representatives", 99)),
"OK": (("Oklahoma Senate", 48), ("Oklahoma House of Representatives", 101)),
"OR": (("Oregon State Senate", 30), ("Oregon House of Representatives", 60)),
"PA": (("Pennsylvania State Senate", 50), ("Pennsylvania House of Representatives", 203)),
"RI": (("Rhode Island Senate", 38), ("Rhode Island House of Representatives", 75)),
"SC": (("South Carolina Senate", 46), ("South Carolina House of Representatives", 124)),
"SD": (("South Dakota Senate", 35), ("South Dakota House of Representatives", 70)),
"TN": (("Tennessee Senate", 33), ("Tennessee House of Representatives", 99)),
"TX": (("Texas Senate", 31), ("Texas House of Representatives", 150)),
"UT": (("Utah State Senate", 29), ("Utah House of Representatives", 75)),
"VT": (("Vermont Senate", 30), ("Vermont House of Representatives", 150)),
"VA": (("Senate of Virginia", 40), ("Virginia House of Delegates", 100)),
"WA": (("Washington State Senate", 49), ("Washington House of Representatives", 98)),
"WV": (("West Virginia Senate", 34), ("West Virginia House of Delegates", 100)),
"WI": (("Wisconsin State Senate", 33), ("Wisconsin State Assembly", 99)),
"WY": (("Wyoming Senate", 31), ("Wyoming House of Representatives", 62)),
}
# States whose legislatures are elected in odd years.
ODD_YEAR_LEGISLATURES = {"LA", "MS", "NJ", "VA"}
# Governors: two-year terms in NH and VT, four elsewhere.
GOVERNOR_TERM_YEARS = {"NH": 2, "VT": 2}
# Month (and day when fixed) a new governor takes office, when it is not January.
# Used only to write the end of a term as "YYYY-MM"; the year always comes from Wikipedia or the term length.
GOVERNOR_INAUGURATION = {"AK": "12", "HI": "12", "KY": "12", "ND": "12-15", "MI": "01-01", "NY": "01-01", "NC": "01-01"}
# Governor election years that are not the even-year November cycle.
GOVERNOR_ODD_YEAR = {"KY", "LA", "MS", "NJ", "VA"}
SENATE_CLASS_BASE_YEAR = {1: 2025, 2: 2027, 3: 2029} # a class-N term ends on Jan 3 of these years, every 6 years
def today():
override = os.environ.get("TODAY") # for tests only, ISO date
return dt.date.fromisoformat(override) if override else dt.date.today()
def election_day(year):
"""Tuesday after the first Monday of November."""
d = dt.date(year, 11, 1)
while d.weekday() != 0:
d += dt.timedelta(days=1)
return d + dt.timedelta(days=1)
def election_window(day):
"""Return the even election year if `day` falls between Election Day and Jan 3 of the next year, else None."""
if day.year % 2 == 0 and day >= election_day(day.year):
return day.year
if day.year % 2 == 1 and day < dt.date(day.year, 1, 3):
return day.year - 1
return None
def last_election_year(day):
"""Most recent even year whose November election has taken place."""
y = day.year if day.year % 2 == 0 else day.year - 1
if day < election_day(y):
y -= 2
return y
def choose_mode(day=None, requested=None):
day = day or today()
requested = (requested or os.environ.get("UPDATE_MODE") or "auto").strip().lower()
if requested not in ("auto", "election", "current"):
raise ValueError(f"UPDATE_MODE must be auto, election or current (got {requested!r})")
if requested == "auto":
return ("election" if election_window(day) else "current"), requested
return requested, requested
def senate_term_end(cls, after):
"""Jan 3 of the first year (class cycle) strictly after the date `after`."""
y = SENATE_CLASS_BASE_YEAR[cls]
while dt.date(y, 1, 3) <= after:
y += 6
while dt.date(y - 6, 1, 3) > after:
y -= 6
return f"{y}-01-03"
def house_term_end(after):
"""Jan 3 of the first odd year strictly after `after`."""
y = after.year if after.year % 2 == 1 else after.year + 1
if dt.date(y, 1, 3) <= after:
y += 2
return f"{y}-01-03"
def senate_class_up(election_year):
"""Regular class elected in a given even year (2024 -> 1, 2026 -> 2, 2028 -> 3)."""
return {2: 1, 4: 2, 0: 3}[election_year % 6]
def governor_term_end(code, year):
md = GOVERNOR_INAUGURATION.get(code, "01")
return f"{year}-{md}"
def next_legislative_election(code, day):
"""Year of the next regular legislative election in a state (odd years in LA, MS, NJ, VA)."""
odd = code in ODD_YEAR_LEGISLATURES
y = day.year
while True:
if (y % 2 == 1) == odd and dt.date(y, 11, 1) > day:
return y
y += 1
# ---------------------------------------------------------------- storage
def ensure_dir():
os.makedirs(DATA_DIR, exist_ok=True)
def path(name):
return os.path.join(DATA_DIR, name)
def write_json_atomic(file_path, obj):
d = os.path.dirname(file_path)
fd, tmp = tempfile.mkstemp(prefix=".tmp-", suffix=".json", dir=d)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=1)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, file_path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def read_json(file_path, default=None):
try:
with open(file_path, encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
return default
def load_category(cat):
return read_json(path(cat + ".json"))
def save_category(cat, data, meta):
write_json_atomic(path(cat + ".json"), {"meta": meta, "data": data})
def seed_governor_powers():
seed = read_json(os.path.join(SEED_DIR, "governors.json"), {}) or {}
return {code: (g or {}).get("powers", []) for code, g in seed.get("data", {}).items()}
def ensure_seed():
"""Copy the seed data into DATA_DIR for every category file that is missing."""
ensure_dir()
copied = []
for cat in CATEGORIES + ["meta"]:
target = path(cat + ".json")
if not os.path.exists(target):
src = os.path.join(SEED_DIR, cat + ".json")
tmp = target + ".seed-tmp"
shutil.copyfile(src, tmp)
os.replace(tmp, target)
copied.append(cat)
return copied
+624
View File
@@ -0,0 +1,624 @@
"""Turn Wikipedia pages into the data the map uses. One function per category and mode.
Every parser returns (data, sources, notes) and raises ParseError when the page does not look as expected.
Validation of totals happens in update.py, not here.
"""
import datetime as dt
import re
import common as C
from wiki import plain, section, sections, split_rows, strip_noise, tables, infobox
STATE_BY_NAME = {n.lower(): c for n, c in C.STATES.items()}
class ParseError(Exception):
pass
def party_code(text):
t = plain(text or "").strip().lower()
if not t:
return None
t = re.sub(r"\s*party.*$", "", t) if "party" in t and not t.startswith("independent") else t
if t in ("d", "dfl") or re.match(r"^(d|dfl)\b", t):
return "D"
if t == "r" or re.match(r"^r\b", t):
return "R"
if t == "i" or re.match(r"^i\b", t):
return "I"
if "independent" in t:
return "I"
if "democrat" in t or "farmer" in t or "dfl" in t:
return "D"
if "republican" in t:
return "R"
return "I"
def state_code(name):
return STATE_BY_NAME.get(plain(name).strip().lower())
# ---------------------------------------------------------------- race rows (Senate, House, governors)
AYE = re.compile(r"\{\{\s*aye\s*\}\}", re.I)
MBY = re.compile(r"\{\{\s*mby\s*\}\}", re.I) # "advanced to runoff" mark
STRIPE = re.compile(r"\{\{\s*party stripe\s*\|([^}|]*)", re.I)
def candidates(row):
"""[(name, party code, won, has a Wikipedia article, advanced to a runoff)] from a results row."""
out = []
for line in row.split("\n"):
st = STRIPE.search(line)
if not st:
continue
won = bool(AYE.search(line))
rest = AYE.sub("", line[st.end():].split("}}", 1)[-1])
bold = re.search(r"'''(.+?)'''", rest)
if bold:
name_src = bold.group(1)
name = plain(name_src)
else:
name_src = rest
name = re.sub(r"\s*\([^()]*\)[\s\d.,%]*$", "", plain(rest)).strip()
pm = re.search(r"(?:'''|\]\])\s*\(([^()]*)\)", rest) or re.search(r"\(([^()]*)\)[\s\d.,%]*$", plain(rest))
party = party_code(pm.group(1)) if pm else party_code(st.group(1))
name = re.sub(r"\s*\((incumbent|write-in)\)", "", name, flags=re.I).strip()
if name:
out.append((name, party, won, "[[" in name_src, bool(MBY.search(line))))
return out
def race_result(row, term_end, elected_status, extra_note=""):
"""Officeholder entry for one race row: winner, or not-yet-called / runoff."""
cands = candidates(row)
winners = [c for c in cands if c[2]]
if len(winners) > 1:
raise ParseError("several winners marked in one race")
if winners:
name, party = winners[0][0], winners[0][1]
return {"name": name, "party": party, "termEnd": term_end, "status": elected_status, "note": extra_note}
text_no_cands = "\n".join(l for l in row.split("\n") if not STRIPE.search(l))
advanced = [c for c in cands if c[4]]
runoff = advanced or re.search(r"run-?off", plain(text_no_cands), re.I)
# the two main candidates: those in the runoff, else notable (linked) Democrats and Republicans first
shown = advanced[:2] or sorted(cands, key=lambda c: (c[1] not in ("D", "R"), not c[3]))[:2]
who = ", ".join(f"{c[0]} ({c[1]})" for c in shown)
parties = {c[1] for c in shown}
if runoff:
m = re.search(r"run-?off[^.]*?((?:January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}(?:, \d{4})?)",
plain(text_no_cands), re.I)
note = "Runoff" + (f" on {m.group(1)}" if m else "") + (f": {who.replace(', ', ' vs ')}" if who else "")
status = "runoff"
else:
note = "Not yet called" + (f"; {who.replace(', ', ' vs ')}" if who else "")
status = "uncalled"
return {"name": None, "party": parties.pop() if len(parties) == 1 and len(shown) > 1 else None,
"termEnd": term_end, "status": status, "note": (note + ". " + extra_note).strip()}
def header_lines(row):
return [l for l in row.split("\n") if l.lstrip().startswith("!")]
# ---------------------------------------------------------------- Senate
def current_senators(client):
title = "List of current United States senators"
text = strip_noise(client.page(title))
start = text.find('id="senators"')
if start < 0:
raise ParseError(f"senator table not found in “{title}”")
start = text.rfind("{|", 0, start)
end = text.find("\n|}", start)
table = text[start:end]
# footnotes saying an independent sits with the Democrats
dem_caucus_efn = set()
for m in re.finditer(r"\{\{efn\|name=([^|}]+)\|(.*?)\}\}\s*$", text, re.M | re.S):
if re.search(r"Democratic Caucus|caucus(es)? with (the )?Democrat", m.group(2), re.I):
dem_caucus_efn.add(m.group(1).strip())
out, state = [], None
for row in split_rows(table)[1:]:
sm = re.search(r"\[\[List of United States senators from ([^|\]]+)\|", row)
if sm:
state = state_code(sm.group(1))
name_line = next((l for l in row.split("\n") if l.startswith("!")), None)
if not name_line or state is None:
continue
name_cell = name_line[1:].split("|", 1)[-1] if re.match(r"!\s*scope", name_line) else name_line[1:]
name = plain(name_cell)
pc = re.search(r"\{\{\s*party color\s*\|([^}]*)\}\}", row, re.I)
cm = re.search(r"Class (\d)", row)
if not cm:
continue
caucus = any(f"name={n}" in row for n in dem_caucus_efn) or re.search(r"Democratic Caucus", row)
out.append({"state": state, "name": name or None, "party": party_code(pc.group(1)) if pc else None,
"class": int(cm.group(1)), "vacant": not name or name.lower().startswith("vacant"),
"demCaucus": bool(caucus)})
if len(out) < 90:
raise ParseError(f"only {len(out)} senators found in “{title}”")
return out, title
def senate_current(client, day):
sens, title = current_senators(client)
data = {}
for s in sens:
entry = {"name": None if s["vacant"] else s["name"], "party": None if s["vacant"] else s["party"],
"termEnd": C.senate_term_end(s["class"], day), "class": s["class"],
"status": "vacant" if s["vacant"] else "continuing",
"note": "Independent, caucuses with Democrats." if s["party"] == "I" and s["demCaucus"] else ""}
data.setdefault(s["state"], []).append(entry)
for v in data.values():
v.sort(key=lambda e: e["class"])
return data, [title]
def senate_election(client, year):
title = f"{year} United States Senate elections"
text = strip_noise(client.page(title))
body = section(text, "Race summary")
if body is None:
raise ParseError(f"“Race summary” section not found in “{title}”")
new_congress = dt.date(year + 1, 1, 3)
regular = C.senate_class_up(year)
races = {}
for row in split_rows(body):
head = "\n".join(header_lines(row))
m = re.search(r"\[\[\s*%d United States Senate (special )?elections? in ([^|\]]+)\|" % year, head)
if not m:
continue
code = state_code(m.group(2))
if not code:
continue
special = bool(m.group(1))
cm = re.search(r"Class (\d)", head)
cls = int(cm.group(1)) if cm else (None if special else regular)
if cls is None:
raise ParseError(f"class of the special election in {C.NAMES[code]} not found")
note = f"Won {year} special election for the remainder of the Class {cls} term." if special else ""
e = race_result(row, C.senate_term_end(cls, new_congress), f"elected-{year}", note)
e["class"] = cls
races[(code, cls)] = e
if len(races) < 30:
raise ParseError(f"only {len(races)} Senate races found in “{title}”")
sens, list_title = current_senators(client)
data = {}
for s in sens:
key = (s["state"], s["class"])
if key in races:
e = dict(races.pop(key))
else:
e = {"name": None if s["vacant"] else s["name"], "party": None if s["vacant"] else s["party"],
"termEnd": C.senate_term_end(s["class"], new_congress), "class": s["class"],
"status": "vacant" if s["vacant"] else "continuing",
"note": "Independent, caucuses with Democrats." if s["party"] == "I" and s["demCaucus"] else ""}
data.setdefault(s["state"], []).append({k: e[k] for k in ("name", "party", "termEnd", "class", "status", "note")})
if races:
raise ParseError("races without a matching seat in the senator list: " + ", ".join(f"{c} class {k}" for c, k in races))
for v in data.values():
v.sort(key=lambda e: e["class"])
return data, [title, list_title]
# ---------------------------------------------------------------- House
def ushr(row):
for l in header_lines(row):
m = re.search(r"\{\{\s*ushr\s*\|\s*(\w\w)\s*\|\s*([\w-]+)", l, re.I)
if m:
d = m.group(2)
return m.group(1).upper(), 0 if not d.isdigit() else int(d)
return None
def house_election(client, year):
title = f"{year} United States House of Representatives elections"
text = strip_noise(client.page(title))
term_end = C.house_term_end(dt.date(year + 1, 1, 3))
data = {}
for head, body in sections(text, 2):
code = state_code(head)
if not code:
continue
reps = []
for row in split_rows(body):
u = ushr(row)
if not u:
continue
e = race_result(row, term_end, f"elected-{year}")
reps.append({"district": u[1], **{k: e[k] for k in ("name", "party", "termEnd", "status", "note")}})
data[code] = reps
if len(data) < 45:
raise ParseError(f"only {len(data)} state sections found in “{title}”")
return data, [title]
def house_current(client, day):
title = "List of current members of the United States House of Representatives"
text = strip_noise(client.page(title))
term_end = C.house_term_end(day)
best = None
for t in tables(text):
if not t.rows:
continue
head = " ".join(c.text.lower() for c in t.rows[0])
if "district" in head and "member" in head and "party" in head and len(t.rows) > 400:
best = t
break
if best is None:
raise ParseError(f"member table not found in “{title}”")
head = [c.text.lower() for c in best.rows[0]]
i_dist = next(i for i, h in enumerate(head) if h.startswith("district"))
i_mem = next(i for i, h in enumerate(head) if h.startswith("member"))
i_party = max(i for i, h in enumerate(head) if h.startswith("party"))
data = {}
for row, raw in zip(best.rows[1:], best.row_raw[1:]):
if len(row) <= max(i_dist, i_mem, i_party) or row[i_dist].header and row[i_dist] is best.rows[0][i_dist]:
continue
dist_raw = row[i_dist].raw
m = re.search(r"\{\{\s*ushr\s*\|\s*(\w\w)\s*\|\s*([\w-]+)", dist_raw, re.I)
if m:
code, d = m.group(1).upper(), m.group(2)
else:
dt_txt = row[i_dist].text
m2 = re.match(r"(.+?)\s+(at-large|\d+)", dt_txt, re.I)
if not m2 or not state_code(m2.group(1)):
continue
code, d = state_code(m2.group(1)), m2.group(2)
if code not in C.APPORTIONMENT:
continue
district = int(d) if d.isdigit() else 0
member = row[i_mem].text
vacant = not member or member.lower().startswith("vacant")
pc = re.search(r"\{\{\s*party color\s*\|([^}]*)\}\}", " ".join(c.raw + " " + c.attrs for c in row), re.I)
party = None if vacant else (party_code(row[i_party].text) or (party_code(pc.group(1)) if pc else None))
note = ""
if vacant:
note = plain(re.sub(r"(?i)^vacant", "", member)).strip(" .–-") or ""
entry = {"district": district, "name": None if vacant else member, "party": party,
"termEnd": term_end, "status": "vacant" if vacant else "continuing", "note": note}
lst = data.setdefault(code, [])
if not any(r["district"] == district for r in lst):
lst.append(entry)
return data, [title]
# ---------------------------------------------------------------- Governors
def current_governors(client):
title = "List of current United States governors"
text = strip_noise(client.page(title))
out = {}
for t in tables(text):
if not t.rows:
continue
head = [c.text.lower() for c in t.rows[0]]
if not any(h.startswith("governor") for h in head) or not any("term end" in h for h in head):
continue
i_gov = next(i for i, h in enumerate(head) if h.startswith("governor"))
i_end = next(i for i, h in enumerate(head) if "term end" in h)
i_party = max((i for i, h in enumerate(head) if h.startswith("party")), default=None)
for row in t.rows[1:]:
st = re.search(r"\[\[\s*Governor of ([^|\]]+)\|", row[0].raw) if row else None
code = state_code(st.group(1)) if st else state_code(row[0].text.split("(")[0]) if row else None
if not code or len(row) <= max(i_gov, i_end):
continue
name = row[i_gov].text
party = None
if i_party is not None and len(row) > i_party:
party = party_code(row[i_party].text)
if not party:
pc = re.search(r"\{\{\s*party color\s*\|([^}]*)\}\}", " ".join(c.attrs for c in row), re.I)
party = party_code(pc.group(1)) if pc else None
end_txt = row[i_end].text
ym = re.search(r"(\d{4})", end_txt)
out[code] = {"name": name or None, "party": party, "endYear": int(ym.group(1)) if ym else None,
"termLimited": "term limit" in end_txt.lower(), "endText": end_txt}
if len(out) >= 50:
break
if len(out) < 45:
raise ParseError(f"only {len(out)} governors found in “{title}”")
return out, title
def _gov_entry(code, g, status, powers):
note = "Term-limited." if g.get("termLimited") else ""
term_end = C.governor_term_end(code, g["endYear"]) if g.get("endYear") else None
return {"name": g["name"], "party": g["party"], "termEnd": term_end, "status": status, "note": note,
"powers": powers.get(code, [])}
def governors_current(client, day):
govs, title = current_governors(client)
powers = C.seed_governor_powers()
data = {code: _gov_entry(code, g, "continuing", powers) for code, g in govs.items()}
return data, [title]
def governors_election(client, year):
title = f"{year} United States gubernatorial elections"
text = strip_noise(client.page(title))
body = section(text, "Race summary")
if body is None:
raise ParseError(f"“Race summary” section not found in “{title}”")
powers = C.seed_governor_powers()
races = {}
for row in split_rows(body):
head = "\n".join(header_lines(row))
m = re.search(r"\[\[\s*%d ([A-Z][A-Za-z .]+?) gubernatorial (?:special )?election\|" % year, head)
if not m:
continue
code = state_code(m.group(1))
if not code:
continue
term = C.GOVERNOR_TERM_YEARS.get(code, 4)
starts_december = C.GOVERNOR_INAUGURATION.get(code, "01").startswith("12")
end_year = year + term if starts_december else year + 1 + term
e = race_result(row, C.governor_term_end(code, end_year), f"elected-{year}",
"End of term deduced from the term length.")
e["powers"] = powers.get(code, [])
races[code] = e
if len(races) < 20:
raise ParseError(f"only {len(races)} governor races found in “{title}”")
govs, list_title = current_governors(client)
data = {}
for code in C.NAMES:
if code in races:
data[code] = races[code]
elif code in govs:
data[code] = _gov_entry(code, govs[code], "continuing", powers)
return data, [title, list_title]
# ---------------------------------------------------------------- State legislatures
LOWER_WORDS = re.compile(r"house|assembly|delegates", re.I)
def chamber_titles():
out = []
for code, (up, low) in C.CHAMBERS.items():
out.append((code, "upper", up[0], up[1]))
if low:
out.append((code, "lower", low[0], low[1]))
return out
GROUP_WORDS = re.compile(r"\b(majority|minority|caucus|coalition|total|officially|nonpartisan)\b", re.I)
PARTY_WORDS = re.compile(r"democrat|republican|independent|vacan|libertarian|green|progressive|dfl", re.I)
def infobox_composition(box):
"""{D, R, I, vacant} from political_groups1 of an Infobox legislature.
Lines are read as groups: a heading (bold or ';' line) with an optional count, then bullet lines.
A bullet without its own count takes the heading's count when it is the heading's only bullet.
"""
pg = box.get("political_groups1") or box.get("political_groups") or ""
groups = [] # [heading label, heading count, [[label, count]]]
for line in pg.split("\n"):
s = line.strip()
if not s:
continue
is_bullet = s.startswith("*") or (s.startswith("|") and not s.startswith("|}"))
txt = plain(s.lstrip("*|; "))
m = re.search(r"^(.*?)\(\s*(\d+)\s*\)\s*$", txt)
label, count = (m.group(1).strip(), int(m.group(2))) if m else (txt.strip(), None)
if is_bullet and (count is not None or PARTY_WORDS.search(label)):
if not groups:
groups.append(["", None, []])
groups[-1][2].append([label, count])
elif s.startswith(("''", ";")) or GROUP_WORDS.search(label) or count is not None:
groups.append([label, count, []])
counts = {"D": 0, "R": 0, "I": 0, "vacant": 0}
found = 0
for head, head_count, bullets in groups:
if len(bullets) == 1 and bullets[0][1] is None and head_count is not None:
bullets[0][1] = head_count
if not bullets and head_count is not None and PARTY_WORDS.search(head) and not GROUP_WORDS.search(head):
bullets = [[head, head_count]]
for label, n in bullets:
if n is None:
continue
if re.search(r"vacan", label, re.I):
counts["vacant"] += n
else:
counts[party_code(label) or "I"] += n
found += 1
return counts if found else None
def chamber_leader(box, which, code):
leaders = []
for i in range(1, 12):
if f"leader{i}" in box:
leaders.append((box.get(f"leader{i}_type", ""), box.get(f"leader{i}", "")))
pick, title, note = None, None, ""
if which == "lower" or code == "NE":
for t, n in leaders:
tp = plain(t)
if re.match(r"speaker\b", tp, re.I) and "pro tem" not in tp.lower():
pick, title = (t, n), ("Speaker of the Legislature" if code == "NE" else "Speaker")
break
if not pick and which == "upper":
lg = False
for t, n in leaders:
tp = plain(t).lower()
is_lg = "lieutenant governor" in t.lower()
if re.match(r"speaker\b", tp) and "pro tem" not in tp:
# Tennessee: the Senate elects its Speaker, who is also lieutenant governor
pick, title = (t, n), "Speaker of the Senate"
note = "Also lieutenant governor." if is_lg else ""
break
if re.match(r"president\b", tp) and "pro tem" not in tp:
if is_lg:
lg = True
continue
pick, title = (t, n), "President of the Senate"
break
if not pick:
for t, n in leaders:
tp = plain(t)
if re.search(r"pro tem|temporary president", tp, re.I):
pick = (t, n)
title = "President pro tempore" if "pro tem" in tp.lower() else "Temporary President"
break
if pick and lg:
note = "Lieutenant governor presides."
if not pick:
others = [l for l in leaders if "lieutenant governor" not in l[0].lower()] or leaders
if not others:
return None
pick = others[0]
title = plain(pick[0]) or "Leader"
txt = plain(pick[1])
m = re.match(r"^(.*?)\s*\(([^()]*)\)\s*$", txt)
name, party = (m.group(1), party_code(m.group(2))) if m else (txt, None)
if not name or name.lower().startswith("vacant"):
return {"title": title, "name": None, "party": None, "termEnd": None, "note": "Vacant.", "status": "vacant"}
if not party:
bg = re.search(r"party color\s*\|([^}]*)\}\}", box.get("background_color", ""), re.I)
if bg and party_code(bg.group(1)) in ("D", "R"):
party = party_code(bg.group(1))
note = (note + " Party deduced from the chamber's majority (not given in the infobox).").strip()
return {"title": title, "name": name.strip(), "party": party, "termEnd": None, "note": note}
def summary_tables(client, year):
"""Post-election compositions from the main state legislative elections page: {(code, which): info}."""
title = f"{year} United States state legislative elections"
text = strip_noise(client.page(title))
out = {}
heads = [(m.start(), plain(m.group(1))) for m in re.finditer(r"^===(?!=)\s*(.+?)\s*===\s*$", text, re.M)]
for t in tables(text):
if not t.caption or not t.rows:
continue
hi = next((i for i, r in enumerate(t.rows[:3]) if any(c.text == "Before" for c in r) and any(c.text == "After" for c in r)), None)
if hi is None:
continue
state = None
for pos, h in heads:
if pos < t.start:
state = h
code = state_code(state or "")
if not code:
continue
which = "upper" if code == "NE" or not LOWER_WORDS.search(t.caption) else "lower"
hdr = [c.text for c in t.rows[hi]]
i_b, i_a = hdr.index("Before"), hdr.index("After")
i_p = max(i for i, h in enumerate(hdr) if h == "Party")
before = {"D": 0, "R": 0, "I": 0, "vacant": 0}
after = {"D": 0, "R": 0, "I": 0, "vacant": 0}
after_known = False
after_missing = False # a party that held seats before has no "After" figure yet
seats = None
for r in t.rows[hi + 1:]:
if len(r) <= max(i_b, i_a, i_p):
continue
label = r[i_p].text
if any(c.text.lower() == "total" for c in r):
nb = re.search(r"\d+", r[i_b].text)
seats = int(nb.group(0)) if nb else None
continue
if not label:
continue
key = "vacant" if re.search(r"vacan", label, re.I) else party_code(label)
nb = re.search(r"\d+", r[i_b].text)
na = re.search(r"\d+", r[i_a].text)
if nb:
before[key] += int(nb.group(0))
if na:
after[key] += int(na.group(0))
after_known = True
elif nb and int(nb.group(0)) > 0 and key != "vacant":
after_missing = True
complete = seats is not None and sum(after.values()) == seats
out[(code, which)] = {"caption": t.caption, "seats": seats, "before": before,
"after": after if after_known and (complete or not after_missing) else None}
if len(out) < 60:
raise ParseError(f"only {len(out)} chamber tables found in “{title}”")
return out, title
def majority_party(c):
top = sorted(("D", "R", "I"), key=lambda k: -c.get(k, 0))
if c.get(top[0], 0) == c.get(top[1], 0):
return None
return top[0]
def fmt_counts(c):
return ", ".join(f"{c[k]} {k}" for k in ("D", "R", "I") if c.get(k))
PARTY_WORD = {"D": "Democrats", "R": "Republicans", "I": "Independents"}
def legislatures(client, mode, day, year=None):
"""Returns ({code: {upper, lower}}, sources, per-chamber problems {(code, which): reason})."""
titles = chamber_titles()
articles = client.pages([t for _, _, t, _ in titles], label="state chamber articles")
summary, summary_title = (summary_tables(client, year) if mode == "election" else ({}, None))
data, problems = {}, {}
for code, which, title, size in titles:
text = articles.get(title)
box = infobox(text, "Infobox legislature") if text else {}
name = plain(box.get("name", "")) or title
leader = chamber_leader(box, which, code) if box else None
next_year = C.next_legislative_election(code, day)
if leader:
leader["termEnd"] = str(next_year)
parts = [leader["note"]]
if mode == "election":
parts.append("Current leader; the leader for the new session may not be chosen yet.")
leader.setdefault("status", "current")
parts.append(f"Leaders serve one legislative session; end deduced from the next regular election ({next_year}).")
leader["note"] = " ".join(p for p in parts if p)
ch = {"name": name, "seats": size, "D": 0, "R": 0, "I": 0, "vacant": 0, "uncalled": 0,
"compositionNote": "", "leader": leader}
s = summary.get((code, which))
if mode == "election" and s:
if s["seats"] and s["seats"] != size:
problems[(code, which)] = f"the summary table gives {s['seats']} seats instead of {size}"
elif s["after"]:
a = s["after"]
known = a["D"] + a["R"] + a["I"] + a["vacant"]
if known > size:
problems[(code, which)] = f"post-election seats add up to {known}, more than {size}"
ch.update({k: a[k] for k in ("D", "R", "I", "vacant")})
ch["uncalled"] = max(0, size - known)
notes = []
if ch["uncalled"]:
notes.append(f"{ch['uncalled']} seat(s) not yet called on Wikipedia.")
mb, ma = majority_party(s["before"]), majority_party(a) if not ch["uncalled"] else None
if mb and ma and mb != ma:
notes.append(f"{PARTY_WORD[ma]} flipped the chamber.")
ch["compositionNote"] = " ".join(notes)
else:
ch["uncalled"] = size
ch["compositionNote"] = (f"Wikipedia has not published {year} results for this chamber yet"
+ (f" (before the election: {fmt_counts(s['before'])})." if fmt_counts(s["before"]) else "."))
ch["_unknown"] = True
else:
comp = infobox_composition(box) if box else None
if not text:
problems[(code, which)] = f"article “{title}” not found"
elif comp is None:
problems[(code, which)] = f"no party composition in the infobox of “{title}”"
else:
ch.update(comp)
total = sum(comp.values())
if total != size:
problems[(code, which)] = f"infobox seats add up to {total} instead of {size}"
if mode == "election":
ch["compositionNote"] = f"No regular election for this chamber in {year}; current composition from the chamber article."
if not leader and (code, which) not in problems:
problems[(code, which)] = f"no presiding officer found in the infobox of “{title}”"
if code == "NE":
ch["compositionNote"] = (ch["compositionNote"] + " Unicameral and officially nonpartisan; counts use members' party affiliation as Wikipedia reports it.").strip()
data.setdefault(code, {"upper": None, "lower": None})[which] = ch
sources = ([summary_title] if summary_title else []) + ["each state chamber's article"]
return data, sources, problems
+738
View File
@@ -0,0 +1,738 @@
{
"meta": {
"mode": "election",
"electionYear": 2026,
"asOf": "2026-11-13",
"seed": true,
"sources": [
"2026 United States gubernatorial elections",
"List of current United States governors",
"each state's Governor article"
]
},
"data": {
"AK": {
"name": "Jonathan Kreiss-Tomkins",
"party": "D",
"termEnd": "2030-12",
"status": "elected-2026",
"note": "Ranked-choice race; Wikipedia marked it called for the Democrat on Nov 13, 2026 (50.2%). Term starts first Monday of December.",
"powers": [
"Veto; override by 2/3 of legislators in joint session",
"Budget bills: override needs 3/4 of elected legislators",
"Line-item and reduction veto on appropriations",
"Commander-in-chief of Alaska's state forces",
"Two consecutive four-year terms"
]
},
"AL": {
"name": "Tommy Tuberville",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; legislature overrides by majority of elected members",
"Amendatory veto and line-item veto",
"Can grant clemency; fills vacancies in elected offices",
"Appoints cabinet and members of 450+ boards and commissions",
"Commander-in-chief of the militia; oversees state finances",
"Two consecutive four-year terms"
]
},
"AR": {
"name": "Sarah Huckabee Sanders",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by simple majority",
"Line-item veto on appropriations bills",
"Appoints the 15 cabinet secretaries",
"Can call the General Assembly into special session",
"Commander-in-chief of the state militia",
"Limited to two four-year terms"
]
},
"AZ": {
"name": "Katie Hobbs",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by 2/3 of elected members (3/4 for some bills)",
"Line-item veto on appropriations",
"Grants pardons, except in impeachment cases",
"Commander-in-chief of state military forces; convenes legislature",
"Two consecutive terms; may run again after four years"
]
},
"CA": {
"name": "Xavier Becerra",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto on budget bills",
"Prepares and submits the annual state budget",
"Appoints state judges to vacant seats",
"Pardons and commutations, some need state Supreme Court approval",
"Commander-in-chief of National Guard; two-term limit"
]
},
"CO": {
"name": "Phil Weiser",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto on appropriations",
"Grants pardons, except for treason or impeachment",
"Commander-in-chief of state military forces",
"Two consecutive terms; eligible again after four years"
]
},
"CT": {
"name": "Ned Lamont",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"No pardon power, unusual among governors",
"Commander-in-chief of state military forces; convenes legislature",
"Four-year terms, no term limit"
]
},
"DE": {
"name": "Matt Meyer",
"party": "D",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by three-fifths of elected members",
"Line-item veto and pocket veto",
"Pardons only on recommendation of the Board of Pardons",
"Commander-in-chief of state military forces; convenes legislature",
"Limited to two terms"
]
},
"FL": {
"name": "Byron Donalds",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds of members present",
"Line-item veto on appropriations",
"Proposes and oversees the state budget",
"Grants pardons (except impeachment); key state appointments",
"Commander-in-chief of Florida National Guard and State Guard",
"Two consecutive four-year terms"
]
},
"GA": {
"name": "Keisha Lance Bottoms",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"Calls the General Assembly into special session",
"Can suspend or remove officers after a commission finding",
"Commander-in-chief of National Guard and State Defense Force",
"Two consecutive terms, then four years out"
]
},
"HI": {
"name": "Josh Green",
"party": "D",
"termEnd": "2030-12",
"status": "elected-2026",
"note": "Term starts first Monday of December.",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item and reduction veto",
"Appoints all state judges, subject to Senate approval",
"Appoints many statewide executives, e.g. attorney general",
"Commander-in-chief of Hawaii's armed forces",
"Two consecutive terms, then must sit out a term"
]
},
"IA": {
"name": "Rob Sand",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto and pocket veto",
"Grants pardons, except treason and impeachment",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"ID": {
"name": "Brad Little",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item veto",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"IL": {
"name": "JB Pritzker",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"Amendatory, line-item and reduction vetoes",
"Reduction vetoes overridden by simple majority",
"Power of pardon and commutation",
"Commander-in-chief of state forces in state service",
"Four-year terms, no term limit"
]
},
"IN": {
"name": "Mike Braun",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; General Assembly overrides by simple majority",
"No line-item veto; pocket veto ruled unconstitutional",
"Pardons and commutations, except treason or impeachment",
"Appoints judges to fill vacancies",
"Can call out the Indiana National Guard in emergencies",
"Two terms in any 12-year period"
]
},
"KS": {
"name": "Cindy Holscher",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "Narrow win, 50.3% to 49.7%; called per Wikipedia.",
"powers": [
"Veto; override by two-thirds of membership",
"Line-item veto",
"Grants pardons; can convene legislature at any time",
"Commander-in-chief of state military forces",
"Two consecutive four-year terms"
]
},
"KY": {
"name": "Andy Beshear",
"party": "D",
"termEnd": "2027-12",
"status": "continuing",
"note": "Term-limited; successor elected Nov 2027, sworn in the fifth Tuesday after the election.",
"powers": [
"Veto; General Assembly overrides by simple majority",
"Line-item veto; no pocket veto",
"Proposes the biennial state budget",
"Broad appointment power over cabinets and commissions",
"Grants pardons, except impeachment cases",
"Two consecutive terms, then four years out"
]
},
"LA": {
"name": "Jeff Landry",
"party": "R",
"termEnd": "2028-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto, required to keep the budget balanced",
"Submits operating budget and five-year capital outlay plan",
"Appoints cabinet secretaries leading state agencies",
"Pardons, reprieves, commutations; commands National Guard",
"Limited to two terms in a lifetime"
]
},
"MA": {
"name": "Maura Healey",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; legislature overrides by two-thirds",
"Line-item, reduction and amendatory vetoes",
"Key appointments need consent of elected Governor's Council",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"MD": {
"name": "Wes Moore",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"Line-item veto on appropriations",
"Presents budget; legislature can cut but not increase it",
"Appoints most officers and cabinet, with Senate consent",
"Pardons and commutations; commands the National Guard",
"Two consecutive four-year terms"
]
},
"ME": {
"name": "Hannah Pingree",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item and reduction veto",
"Appoints judges and officers, confirmed by the Legislature",
"Pardons, reprieves and commutations, except impeachment",
"Commander-in-chief of the Maine National Guard",
"Two consecutive four-year terms"
]
},
"MI": {
"name": "Jocelyn Benson",
"party": "D",
"termEnd": "2031-01-01",
"status": "elected-2026",
"note": "Term begins at noon on January 1.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto",
"Appoints judges, later subject to voter ratification",
"Appoints most department heads with Senate consent",
"Grants pardons (except impeachment); commands state militia",
"Limited to two four-year terms"
]
},
"MN": {
"name": "Amy Klobuchar",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "Minnesota Democratic-Farmer-Labor Party (Democratic affiliate).",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto and pocket veto",
"Appoints department heads (commissioners)",
"Four-year terms, no term limit"
]
},
"MO": {
"name": "Mike Kehoe",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto",
"Grants pardons, except impeachment cases",
"Commander-in-chief of the National Guard; convenes legislature",
"Limited to two terms"
]
},
"MS": {
"name": "Tate Reeves",
"party": "R",
"termEnd": "2028-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto on appropriations only",
"Pardons and reprieves, except treason or impeachment",
"Little authority over the state budget process",
"Commander-in-chief of National Guard; calls special sessions",
"Two consecutive four-year terms"
]
},
"MT": {
"name": "Greg Gianforte",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item and amendatory vetoes",
"Grants pardons and reprieves",
"Commander-in-chief; can convene legislature at any time",
"Eight years in any sixteen-year period"
]
},
"NC": {
"name": "Josh Stein",
"party": "D",
"termEnd": "2029-01-01",
"status": "continuing",
"note": "Term begins January 1.",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"No line-item veto",
"Director of the state budget",
"Appoints some judges, executive officials and board members",
"Grants pardons; commands the North Carolina National Guard",
"Two consecutive four-year terms"
]
},
"ND": {
"name": "Kelly Armstrong",
"party": "R",
"termEnd": "2028-12-15",
"status": "continuing",
"note": "Next inauguration fixed on December 15, 2028.",
"powers": [
"Veto; Legislative Assembly overrides by two-thirds",
"Line-item veto",
"Can call the Legislative Assembly into emergency session",
"Commander-in-chief of state military forces",
"Limited to two four-year terms"
]
},
"NE": {
"name": "Jim Pillen",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; unicameral Legislature overrides by three-fifths (30 votes)",
"Line-item and reduction veto",
"Calls special sessions limited to topics in proclamation",
"Two consecutive four-year terms"
]
},
"NH": {
"name": "Kelly Ayotte",
"party": "R",
"termEnd": "2029-01",
"status": "elected-2026",
"note": "Two-year term.",
"powers": [
"Veto; override by two-thirds of members present",
"No line-item veto",
"Pardons need approval of the elected Executive Council",
"Nominates judges, attorney general, Guard officers (Council approval)",
"Commander-in-chief of state military forces",
"Two-year terms, no term limit"
]
},
"NJ": {
"name": "Mikie Sherrill",
"party": "D",
"termEnd": "2030-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item and amendatory vetoes",
"Appoints entire cabinet, confirmed by the Senate",
"Appoints all Superior Court judges and county prosecutors",
"Commander-in-chief of the New Jersey National Guard",
"Two consecutive four-year terms"
]
},
"NM": {
"name": "Deb Haaland",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item veto",
"Submits the state budget",
"Commander-in-chief of the New Mexico National Guard",
"Two consecutive terms; may run again after one term out"
]
},
"NV": {
"name": "Aaron Ford",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by two-thirds of elected members",
"No line-item veto",
"Pardons and reprieves, except treason or impeachment",
"Commander-in-chief; can convene legislature at any time",
"Limited to two four-year terms"
]
},
"NY": {
"name": "Kathy Hochul",
"party": "D",
"termEnd": "2031-01-01",
"status": "elected-2026",
"note": "Terms begin at midnight on New Year's Day.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto and pocket veto",
"Grants pardons, except treason and impeachment",
"Appoints Executive Chamber without Senate confirmation",
"Commander-in-chief; can convene the Legislature",
"Four-year terms, no term limit"
]
},
"OH": {
"name": "Amy Acton",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"Line-item veto",
"Drafts the budget proposal for the General Assembly",
"Grants pardons, except treason and impeachment",
"Appointments with Senate consent; fills statewide vacancies",
"Two consecutive four-year terms"
]
},
"OK": {
"name": "Mike Mazzei",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto on appropriations",
"Pardons only after a favorable Pardon and Parole Board vote",
"Prepares the state budget; appoints cabinet secretaries",
"Appoints appellate judges from nominating commission lists",
"Two consecutive four-year terms"
]
},
"OR": {
"name": "Tina Kotek",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by two-thirds in both houses",
"Line-item veto on appropriation and emergency bills",
"Pardons and commutations; only reprieves for treason",
"Commander-in-chief of the Oregon Military Department",
"Calls special sessions; fills vacancies by appointment",
"Two terms in any 12-year period"
]
},
"PA": {
"name": "Josh Shapiro",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"Two consecutive four-year terms",
"No lifetime limit; may return after a break"
]
},
"RI": {
"name": "Helena Foulkes",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; override by three-fifths of members present",
"No line-item veto",
"Grants pardons",
"Submits the annual state budget",
"Commander-in-chief (Captain-General) of the National Guard",
"Two consecutive four-year terms"
]
},
"SC": {
"name": "Alan Wilson",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"Submits an executive budget each January",
"Appoints 14 cabinet agency directors; shares other appointments",
"Clemency limited to commuting death sentences to life",
"Two consecutive four-year terms"
]
},
"SD": {
"name": "Larry Rhoden",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto; amendatory veto on style or form only",
"Appoints cabinet and many boards and commissions",
"Grants pardons for state offenses",
"Commander-in-chief of the South Dakota National Guard",
"Two consecutive four-year terms"
]
},
"TN": {
"name": "Marsha Blackburn",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "Won with a 45.5% plurality.",
"powers": [
"Veto; General Assembly overrides by simple majority",
"Line-item veto on spending items",
"Appoints judges through the Tennessee Plan nominating commission",
"Appoints most state department heads",
"Commander-in-chief of National Guard and state militia",
"Two consecutive four-year terms"
]
},
"TX": {
"name": "Gina Hinojosa",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds of members present",
"Line-item veto",
"Pardons only on Board of Pardons and Paroles recommendation",
"Weak budget role; Legislative Budget Board leads",
"Commander-in-chief of Texas Military Forces; calls special sessions",
"Four-year terms, no term limit"
]
},
"UT": {
"name": "Spencer Cox",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto",
"Commander-in-chief of the Utah National Guard",
"Convenes the legislature on extraordinary occasions",
"No term limits (repealed in 2003)"
]
},
"VA": {
"name": "Abigail Spanberger",
"party": "D",
"termEnd": "2030-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item and amendatory vetoes",
"Pardons and commutes sentences",
"Fills vacancies not appointed by the legislature",
"Commander-in-chief of the Virginia National Guard",
"Single four-year term; no immediate re-election"
]
},
"VT": {
"name": "Phil Scott",
"party": "R",
"termEnd": "2029-01",
"status": "elected-2026",
"note": "Two-year term.",
"powers": [
"Veto; override by two-thirds of members present",
"No line-item veto",
"Pardons and remits fines; only reprieves for treason",
"Commissions or appoints state officers",
"Captain-General and Commander-in-Chief of state forces",
"Two-year terms, no term limit"
]
},
"WA": {
"name": "Bob Ferguson",
"party": "D",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of members present",
"Section veto on any bill; line-item on spending",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"WI": {
"name": "David Crowley",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds of members present",
"Strong partial veto: strikes words in appropriation bills",
"Pardons, commutations, reprieves, except treason or impeachment",
"Appoints heads of agencies created by the legislature",
"Commander-in-chief of the Wisconsin National Guard",
"Four-year terms, no term limits"
]
},
"WV": {
"name": "Patrick Morrisey",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislature overrides by majority of elected members",
"Line-item and reduction veto",
"Pardons and reprieves, except House impeachment cases",
"Commander-in-chief; can convene the legislature at any time",
"Two consecutive four-year terms"
]
},
"WY": {
"name": "Eric Barlow",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds of elected members",
"Line-item veto",
"Commander-in-chief of the Wyoming National Guard",
"Eight years in any sixteen-year period"
]
}
}
}
+3594
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
{
"lastRun": null,
"seedFooter": "Data: English Wikipedia (2026 U.S. Senate, House, gubernatorial and state legislative election articles, the current-officeholder lists and each state's “Governor of …” and legislature articles), read on November 13, 2026, ten days after the election. Results that were not final on that date are marked “Not yet called”. State legislature leaders for 2027 are often chosen in December or January; where none was named yet, the current leader is shown and noted."
}
+914
View File
@@ -0,0 +1,914 @@
{
"meta": {
"mode": "election",
"electionYear": 2026,
"asOf": "2026-11-13",
"seed": true,
"sources": [
"2026 United States Senate elections",
"List of current United States senators"
]
},
"data": {
"AK": [
{
"name": "Undecided (Mary Peltola vs. Dan Sullivan)",
"party": null,
"termEnd": "2033-01-03",
"class": 2,
"status": "uncalled",
"note": "Not called as of Nov 12, 2026. Unofficial first-choice count (Nov 12): Mary Peltola (D) 49.10%, Dan S. Sullivan (R, incumbent) 46.80%; ranked-choice tabulation may follow if no one passes 50%. Late absentee ballots accepted up to 15 days after Election Day."
},
{
"name": "Lisa Murkowski",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"AL": [
{
"name": "Barry Moore",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Katie Britt",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"AR": [
{
"name": "Tom Cotton",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "John Boozman",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"AZ": [
{
"name": "Ruben Gallego",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Mark Kelly",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"CA": [
{
"name": "Adam Schiff",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Alex Padilla",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"CO": [
{
"name": "John Hickenlooper",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Michael Bennet",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"CT": [
{
"name": "Chris Murphy",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Richard Blumenthal",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"DE": [
{
"name": "Lisa Blunt Rochester",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Chris Coons",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"FL": [
{
"name": "Rick Scott",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ashley Moody",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "elected-2026",
"note": "Won 2026 special election for remainder of Class 3 term."
}
],
"GA": [
{
"name": "Jon Ossoff",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Raphael Warnock",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"HI": [
{
"name": "Mazie Hirono",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Brian Schatz",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"IA": [
{
"name": "Josh Turek",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Chuck Grassley",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"ID": [
{
"name": "Jim Risch",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Mike Crapo",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"IL": [
{
"name": "Juliana Stratton",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Tammy Duckworth",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"IN": [
{
"name": "Jim Banks",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Todd Young",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"KS": [
{
"name": "Adam Hamilton",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Jerry Moran",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"KY": [
{
"name": "Andy Barr",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Rand Paul",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"LA": [
{
"name": "Julia Letlow",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "John Kennedy",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"MA": [
{
"name": "Elizabeth Warren",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ed Markey",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MD": [
{
"name": "Angela Alsobrooks",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Chris Van Hollen",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"ME": [
{
"name": "Angus King",
"party": "I",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Independent, caucuses with Democrats."
},
{
"name": "Troy Jackson",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MI": [
{
"name": "Elissa Slotkin",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Abdul El-Sayed",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MN": [
{
"name": "Amy Klobuchar",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Elected Governor of Minnesota in 2026 (takes office Jan 4, 2027); seat expected to be filled by appointment, successor not yet named."
},
{
"name": "Peggy Flanagan",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MO": [
{
"name": "Josh Hawley",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Eric Schmitt",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"MS": [
{
"name": "Roger Wicker",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Scott Colom",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MT": [
{
"name": "Tim Sheehy",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Kurt Alme",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NC": [
{
"name": "Roy Cooper",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Ted Budd",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"ND": [
{
"name": "Kevin Cramer",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "John Hoeven",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"NE": [
{
"name": "Deb Fischer",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Pete Ricketts",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NH": [
{
"name": "Chris Pappas",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Maggie Hassan",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"NJ": [
{
"name": "Andy Kim",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Cory Booker",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NM": [
{
"name": "Martin Heinrich",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ben Ray Luján",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NV": [
{
"name": "Jacky Rosen",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Catherine Cortez Masto",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"NY": [
{
"name": "Kirsten Gillibrand",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Chuck Schumer",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"OH": [
{
"name": "Bernie Moreno",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Sherrod Brown",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "elected-2026",
"note": "Won 2026 special election for remainder of Class 3 term."
}
],
"OK": [
{
"name": "Kevin Hern",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "James Lankford",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"OR": [
{
"name": "Jeff Merkley",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Ron Wyden",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"PA": [
{
"name": "Dave McCormick",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "John Fetterman",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"RI": [
{
"name": "Sheldon Whitehouse",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Jack Reed",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"SC": [
{
"name": "Annie Andrews",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Tim Scott",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"SD": [
{
"name": "Mike Rounds",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "John Thune",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"TN": [
{
"name": "Marsha Blackburn",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Elected Governor of Tennessee in 2026 (takes office Jan 16, 2027); seat expected to be filled by appointment, successor not yet named."
},
{
"name": "Bill Hagerty",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"TX": [
{
"name": "Ted Cruz",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "James Talarico",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"UT": [
{
"name": "John Curtis",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Mike Lee",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"VA": [
{
"name": "Tim Kaine",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Mark Warner",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"VT": [
{
"name": "Bernie Sanders",
"party": "I",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Independent, caucuses with Democrats."
},
{
"name": "Peter Welch",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"WA": [
{
"name": "Maria Cantwell",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Patty Murray",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"WI": [
{
"name": "Tammy Baldwin",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ron Johnson",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"WV": [
{
"name": "Jim Justice",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Shelley Moore Capito",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"WY": [
{
"name": "John Barrasso",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Harriet Hageman",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
]
}
}
+220
View File
@@ -0,0 +1,220 @@
"""Small web server: the map page, its data, and a button-triggered update from Wikipedia."""
import datetime as dt
import json
import mimetypes
import os
import sys
import threading
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import common as C
import update as U
STATIC = os.path.join(C.APP_DIR, "static")
PORT = int(os.environ.get("PORT", "8080"))
MODE_LABEL = {"election": "{year} election results", "current": "current officeholders"}
class UpdateJob:
"""One update at a time, run in a background thread; keeps its progress for the status endpoint."""
def __init__(self):
self.lock = threading.Lock()
self.state = "idle"
self.messages = []
self.warnings = []
self.error = None
self.started = None
self.finished = None
self.thread = None
def start(self):
with self.lock:
if self.state == "running" or U.lock_held():
return False
self.state, self.messages, self.warnings, self.error = "running", [], [], None
self.started, self.finished = U.now_iso(), None
self.thread = threading.Thread(target=self._run, daemon=True)
self.thread.start()
return True
def _progress(self, msg):
print(msg, flush=True)
with self.lock:
self.messages.append(msg)
del self.messages[:-200]
def _run(self):
try:
run = U.run_update(progress=self._progress)
with self.lock:
self.warnings = run["warnings"]
self.state = "done"
except U.Busy as e:
with self.lock:
self.state, self.error = "failed", str(e)
except Exception as e: # report anything unexpected in plain words, details go to the log
traceback.print_exc()
with self.lock:
self.state = "failed"
self.error = f"The update stopped because of an unexpected error ({type(e).__name__}: {e}). Previous data was kept."
finally:
with self.lock:
self.finished = U.now_iso()
def status(self):
with self.lock:
running_elsewhere = self.state != "running" and U.lock_held()
return {"state": "running" if running_elsewhere else self.state,
"runningElsewhere": running_elsewhere,
"startedAt": self.started, "finishedAt": self.finished,
"messages": list(self.messages), "warnings": list(self.warnings), "error": self.error}
JOB = UpdateJob()
def long_date(iso):
d = dt.date.fromisoformat(iso[:10])
return f"{d:%B} {d.day}, {d.year}"
def merged_data():
cats = {cat: (C.load_category(cat) or {"meta": {}, "data": {}}) for cat in C.CATEGORIES}
meta_file = C.read_json(C.path("meta.json"), {}) or {}
powers = C.seed_governor_powers()
data = {}
for code in C.NAMES:
gov = cats["governors"]["data"].get(code)
if gov is not None and not gov.get("powers"):
gov = dict(gov, powers=powers.get(code, []))
leg = cats["legislatures"]["data"].get(code)
data[code] = {"senators": cats["senate"]["data"].get(code, []),
"house": cats["house"]["data"].get(code, []),
"gov": gov, "leg": leg}
metas = {cat: cats[cat]["meta"] for cat in C.CATEGORIES}
modes = {m.get("mode") for m in metas.values()}
years = {m.get("electionYear") for m in metas.values() if m.get("mode") == "election"}
dates = sorted(m.get("asOf", "")[:10] for m in metas.values() if m.get("asOf"))
mode = modes.pop() if len(modes) == 1 else "mixed"
year = max(years) if years else None
last = meta_file.get("lastRun") or {}
sources = []
for m in metas.values():
for s in m.get("sources", []):
if s not in sources:
sources.append(s)
if all(m.get("seed") for m in metas.values()):
footer = meta_file.get("seedFooter", "")
else:
if dates and dates[0] != dates[-1]:
read = f", read between {long_date(dates[0])} and {long_date(dates[-1])}."
else:
read = f", read on {long_date(dates[0])}." if dates else "."
footer = "Data: English Wikipedia (" + "; ".join(sources) + ")" + read
if mode in ("election", "mixed"):
footer += " Results that were not final on that date are marked “Not yet called”. Where a chamber's leader for the new session was not chosen yet, the current leader is shown and noted."
footer += " Map shapes: us-atlas (U.S. Census Bureau boundaries)."
meta = {
"mode": mode,
"electionYear": year,
"electionDay": C.election_day(year).isoformat() if year else None,
"modeLabel": "mixed sources (see warnings)" if mode == "mixed" else MODE_LABEL.get(mode, mode).format(year=year),
"asOf": dates[0] if dates else None,
"newest": dates[-1] if dates else None,
"categories": {cat: {"mode": m.get("mode"), "asOf": m.get("asOf"), "electionYear": m.get("electionYear")}
for cat, m in metas.items()},
"lastRun": last or None,
"warnings": (last.get("warnings") if last else []) or [],
"footer": footer,
}
return {"data": data, "meta": meta}
class Handler(BaseHTTPRequestHandler):
server_version = "us-officeholders-map/1.0"
def log_message(self, fmt, *args):
sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args))
def _send(self, code, body, ctype="application/json; charset=utf-8", extra=None):
if isinstance(body, (dict, list)):
body = json.dumps(body, ensure_ascii=False).encode("utf-8")
elif isinstance(body, str):
body = body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store" if ctype.startswith("application/json") else "public, max-age=300")
self.send_header("X-Content-Type-Options", "nosniff")
for k, v in (extra or {}).items():
self.send_header(k, v)
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def _static(self, rel):
full = os.path.realpath(os.path.join(STATIC, rel))
if not full.startswith(os.path.realpath(STATIC) + os.sep) or not os.path.isfile(full):
return self._send(404, {"error": "Not found"})
ctype = mimetypes.guess_type(full)[0] or "application/octet-stream"
if ctype.startswith("text/") or ctype in ("application/javascript", "application/json"):
ctype += "; charset=utf-8"
with open(full, "rb") as f:
body = f.read()
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-cache" if rel == "index.html" else "public, max-age=3600")
self.send_header("X-Content-Type-Options", "nosniff")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def do_HEAD(self):
self.do_GET()
def do_GET(self):
p = self.path.split("?", 1)[0]
if p in ("/", "/index.html"):
return self._static("index.html")
if p.startswith("/static/"):
return self._static(p[len("/static/"):])
if p == "/api/data":
try:
return self._send(200, merged_data())
except Exception as e:
traceback.print_exc()
return self._send(500, {"error": f"Could not read the stored data ({e})."})
if p == "/api/update/status":
return self._send(200, JOB.status())
return self._send(404, {"error": "Not found"})
def do_POST(self):
p = self.path.split("?", 1)[0]
if p != "/api/update":
return self._send(404, {"error": "Not found"})
# Plain cross-site form posts cannot set this header, so another web page cannot start updates.
if self.headers.get("X-Requested-With") != "us-officeholders-map":
return self._send(403, {"error": "Missing request header."})
length = int(self.headers.get("Content-Length") or 0)
if length:
self.rfile.read(min(length, 4096))
if JOB.start():
return self._send(202, {"started": True})
return self._send(409, {"started": False, "error": "An update is already running."})
def main():
copied = C.ensure_seed()
if copied:
print(f"Seeded {C.DATA_DIR} with: {', '.join(copied)}", flush=True)
httpd = ThreadingHTTPServer(("0.0.0.0", PORT), Handler)
print(f"Serving on port {PORT}, data in {C.DATA_DIR}", flush=True)
httpd.serve_forever()
if __name__ == "__main__":
main()
+534
View File
@@ -0,0 +1,534 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>US Officeholders 2027</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<style>
/* Layout: civic reference sheet. Header + mode switch, then map (left) beside a sticky detail panel (right); stacks on phones. */
:root {
--bg: #f6f7f9;
--surface: #ffffff;
--fg: #1b1f27;
--muted: #5d6573;
--line: #dde1e8;
--map-empty: #e4e7ec;
--map-stroke: #ffffff;
--rep: #c8253b;
--dem: #2457b8;
--ind: #7a46b0;
--unk: #9aa1ad;
--focus: #e0a100;
--font: "Public Sans", "Segoe UI", system-ui, -apple-system, sans-serif;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #12151b; --surface: #1a1e26; --fg: #e9ecf1; --muted: #9ba3b1; --line: #2c323d;
--map-empty: #2a303b; --map-stroke: #12151b;
--rep: #e2475b; --dem: #4f80e0; --ind: #a174d6; --unk: #6c7482; --focus: #f2bf3a;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #12151b; --surface: #1a1e26; --fg: #e9ecf1; --muted: #9ba3b1; --line: #2c323d;
--map-empty: #2a303b; --map-stroke: #12151b;
--rep: #e2475b; --dem: #4f80e0; --ind: #a174d6; --unk: #6c7482; --focus: #f2bf3a;
color-scheme: dark;
}
* { box-sizing: border-box; }
body {
background: var(--bg); color: var(--fg); font-family: var(--font); font-size: 15px; line-height: 1.5;
padding-left: max(16px, env(safe-area-inset-left, 0px));
padding-right: max(16px, env(safe-area-inset-right, 0px));
padding-block: 20px 40px;
}
.wrap { max-width: 1320px; margin: 0 auto; display: grid; gap: 18px; }
header { display: grid; gap: 6px; }
h1 { margin: 0; font-size: clamp(1.6rem, 3.2vw, 2.3rem); font-weight: 800; letter-spacing: -0.02em; text-wrap: balance; }
.lede { margin: 0; color: var(--muted); max-width: 72ch; }
.lede a { color: inherit; }
.modes { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.modes .label { font-size: 0.75rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); margin-right: 4px; }
.modes button {
font: inherit; font-size: 0.9rem; font-weight: 600; padding: 7px 14px; border-radius: 999px;
border: 1px solid var(--line); background: var(--surface); color: var(--fg); cursor: pointer;
}
.modes button[aria-pressed="true"] { background: var(--fg); color: var(--bg); border-color: var(--fg); }
.modes button:focus-visible, .state:focus-visible, .chip:focus-visible, select:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.main { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); gap: 20px; align-items: start; }
@media (max-width: 900px) { .main { grid-template-columns: minmax(0, 1fr); } }
.mapcard { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 14px; display: grid; gap: 12px; min-width: 0; }
.totals { display: flex; flex-wrap: wrap; gap: 6px 18px; align-items: baseline; }
.totals .t-title { font-weight: 700; }
.totals .t-sub { color: var(--muted); font-size: 0.85rem; }
svg.map { width: 100%; height: auto; display: block; }
.state { stroke: var(--map-stroke); stroke-width: 1; cursor: pointer; transition: filter 0.12s; }
.state:hover { filter: brightness(1.08) saturate(1.1); }
.state.sel { stroke: var(--fg); stroke-width: 2.4; }
.lbl { font: 700 11px var(--font); fill: #fff; pointer-events: none; text-anchor: middle; dominant-baseline: central; paint-order: stroke; stroke: rgba(0,0,0,0.28); stroke-width: 2px; }
.lbl.dark { fill: var(--fg); stroke: none; }
.chip rect { stroke: var(--map-stroke); stroke-width: 1; }
.chip { cursor: pointer; }
.chip.sel rect { stroke: var(--fg); stroke-width: 2.2; }
.legend { display: flex; flex-wrap: wrap; gap: 6px 16px; font-size: 0.85rem; color: var(--muted); align-items: center; }
.legend .sw { display: inline-block; width: 14px; height: 14px; border-radius: 3px; vertical-align: -2px; margin-right: 6px; }
.picker { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: 0.9rem; color: var(--muted); }
select { font: inherit; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface); color: var(--fg); }
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 18px; min-width: 0; }
@media (min-width: 901px) { .panel { position: sticky; top: calc(env(safe-area-inset-top, 0px) + 12px); max-height: calc(100vh - 24px); overflow-y: auto; } }
.panel h2 { margin: 0 0 2px; font-size: 1.5rem; font-weight: 800; letter-spacing: -0.01em; }
.panel .sub { color: var(--muted); margin: 0 0 12px; font-size: 0.88rem; }
.cat { border-top: 1px solid var(--line); padding-block: 12px; display: grid; gap: 6px; }
.cat h3 { margin: 0; font-size: 0.75rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
.cat .chamber { font-size: 0.85rem; color: var(--muted); }
ul.people { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
ul.people li { display: grid; grid-template-columns: 14px minmax(0, 1fr) auto; gap: 8px; align-items: baseline; }
ul.people .who { min-width: 0; }
ul.people .dist { color: var(--muted); font-size: 0.82rem; font-variant-numeric: tabular-nums; margin-right: 4px; }
ul.people .end { color: var(--muted); font-size: 0.82rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
ul.people .role { display: block; color: var(--muted); font-size: 0.8rem; }
.note { display: block; color: var(--muted); font-size: 0.78rem; font-style: italic; }
.tag { display: inline-block; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; padding: 1px 6px; border-radius: 4px; border: 1px solid var(--line); color: var(--muted); margin-left: 4px; vertical-align: 1px; }
.sq { display: inline-block; width: 12px; height: 12px; border-radius: 2px; background: var(--unk); vertical-align: -1px; flex: none; }
.sq.D { background: var(--dem); } .sq.R { background: var(--rep); } .sq.I { background: var(--ind); }
.sq.U { background: repeating-linear-gradient(45deg, var(--unk) 0 2px, transparent 2px 4px); border: 1px solid var(--unk); }
.sum { font-weight: 700; font-variant-numeric: tabular-nums; display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: center; padding-top: 2px; }
.sum span.item { display: inline-flex; gap: 6px; align-items: center; }
.sum .extra { font-weight: 400; color: var(--muted); font-size: 0.82rem; }
ul.powers { margin: 4px 0 0; padding-left: 18px; display: grid; gap: 3px; font-size: 0.9rem; }
.overview .row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; padding-block: 8px; border-top: 1px solid var(--line); }
.overview .row:first-of-type { border-top: 0; }
.hint { color: var(--muted); font-size: 0.88rem; margin: 12px 0 0; }
.tip { position: fixed; pointer-events: none; background: var(--fg); color: var(--bg); font-size: 0.82rem; padding: 6px 9px; border-radius: 6px; max-width: 260px; z-index: 5; }
footer { color: var(--muted); font-size: 0.8rem; max-width: 90ch; }
@media (prefers-reduced-motion: reduce) { .state { transition: none; } }
/* update from Wikipedia */
.updatebar { display: flex; flex-wrap: wrap; gap: 8px 14px; align-items: center; margin-top: 4px; }
.updatebar button {
font: inherit; font-size: 0.9rem; font-weight: 700; padding: 7px 14px; border-radius: 8px;
border: 1px solid var(--fg); background: var(--fg); color: var(--bg); cursor: pointer;
}
.updatebar button:disabled { opacity: 0.6; cursor: progress; }
.updatebar button:focus-visible, details.warn summary:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.datainfo { color: var(--muted); font-size: 0.88rem; }
.upstatus { font-size: 0.88rem; padding: 8px 12px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface); max-width: 90ch; }
.upstatus.error { border-color: var(--rep); }
.upstatus.ok { border-color: var(--dem); }
.upstatus .spin { display: inline-block; width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--muted); border-top-color: transparent; margin-right: 8px; animation: spin 0.9s linear infinite; vertical-align: -1px; }
@keyframes spin { to { transform: rotate(360deg); } }
details.warn { font-size: 0.86rem; color: var(--muted); max-width: 90ch; }
details.warn summary { cursor: pointer; font-weight: 600; color: var(--fg); }
details.warn ul { margin: 6px 0 0; padding-left: 18px; display: grid; gap: 4px; }
@media (prefers-reduced-motion: reduce) { .upstatus .spin { animation: none; } }
</style>
<div class="wrap">
<header>
<h1 id="title">US Officeholders</h1>
<p class="lede" id="lede">Loading the data…</p>
<div class="updatebar">
<button type="button" id="updateBtn">Update from Wikipedia</button>
<span class="datainfo" id="dataInfo"></span>
</div>
<div class="upstatus" id="upStatus" role="status" aria-live="polite" hidden></div>
<details class="warn" id="warnBox" hidden><summary id="warnSummary"></summary><ul id="warnList"></ul></details>
</header>
<div class="modes" role="group" aria-label="Color the map by">
<span class="label">Color map by</span>
<button type="button" data-mode="gov" aria-pressed="true">Governor</button>
<button type="button" data-mode="sen">U.S. Senate</button>
<button type="button" data-mode="house">U.S. House</button>
<button type="button" data-mode="upper">State Senate</button>
<button type="button" data-mode="lower">State House</button>
</div>
<div class="main">
<section class="mapcard" aria-label="Map">
<div class="totals" id="totals"></div>
<svg class="map" id="map" viewBox="-10 0 1060 615" role="group" aria-label="Map of US states">
<defs>
<pattern id="p-split" patternUnits="userSpaceOnUse" width="8" height="8" patternTransform="rotate(45)">
<rect width="4" height="8" fill="var(--dem)"></rect><rect x="4" width="4" height="8" fill="var(--rep)"></rect>
</pattern>
<pattern id="p-unk" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
<rect width="6" height="6" fill="var(--map-empty)"></rect><rect width="2" height="6" fill="var(--unk)"></rect>
</pattern>
</defs>
<g id="states"></g>
<g id="labels"></g>
<g id="chips"></g>
</svg>
<div class="legend" id="legend"></div>
<div class="picker">
<label for="statePick">Or pick a state</label>
<select id="statePick"><option value="">United States (overview)</option></select>
</div>
</section>
<aside class="panel" id="panel" aria-live="polite"></aside>
</div>
<footer id="foot"></footer>
</div>
<div class="tip" id="tip" hidden></div>
<script src="/static/vendor/d3.min.js"></script>
<script src="/static/vendor/topojson.min.js"></script>
<script>
let GEO = null, DATA = {}, META = {};
let app = null;
/* ---------- texts that depend on the data mode ---------- */
const LONG_MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
function longDate(iso) { const m = String(iso || "").match(/^(\d{4})-(\d{2})-(\d{2})/); return m ? `${LONG_MONTHS[+m[2] - 1]} ${+m[3]}, ${m[1]}` : ""; }
function isElection() { return META.mode === "election" && META.electionYear; }
function fromWhen() { return isElection() ? `from January ${META.electionYear + 1}` : "today"; }
function periodText() { return isElection() ? `Officeholders from January ${META.electionYear + 1}` : "Current officeholders"; }
function applyMeta() {
const title = isElection() ? `US Officeholders ${META.electionYear + 1}` : "US Officeholders";
document.title = title;
document.getElementById("title").textContent = title;
const after = isElection() ? `, after the ${longDate(META.electionDay)} elections` : "";
document.getElementById("lede").textContent = `Who represents each state ${fromWhen()}${after}: U.S. senators, U.S. representatives, state senators, state representatives and the governor. Click a state to see names and term ends. Source: English Wikipedia, read on ${longDate(META.asOf) || "an unknown date"}.`;
document.getElementById("dataInfo").textContent = `Data as of ${fmtDate(META.asOf)} · source: ${META.modeLabel || "unknown"}`;
document.getElementById("foot").textContent = META.footer || "";
showWarnings(META.warnings || [], "from the last update");
}
const CODES = {"Alabama":"AL","Alaska":"AK","Arizona":"AZ","Arkansas":"AR","California":"CA","Colorado":"CO","Connecticut":"CT","Delaware":"DE","Florida":"FL","Georgia":"GA","Hawaii":"HI","Idaho":"ID","Illinois":"IL","Indiana":"IN","Iowa":"IA","Kansas":"KS","Kentucky":"KY","Louisiana":"LA","Maine":"ME","Maryland":"MD","Massachusetts":"MA","Michigan":"MI","Minnesota":"MN","Mississippi":"MS","Missouri":"MO","Montana":"MT","Nebraska":"NE","Nevada":"NV","New Hampshire":"NH","New Jersey":"NJ","New Mexico":"NM","New York":"NY","North Carolina":"NC","North Dakota":"ND","Ohio":"OH","Oklahoma":"OK","Oregon":"OR","Pennsylvania":"PA","Rhode Island":"RI","South Carolina":"SC","South Dakota":"SD","Tennessee":"TN","Texas":"TX","Utah":"UT","Vermont":"VT","Virginia":"VA","Washington":"WA","West Virginia":"WV","Wisconsin":"WI","Wyoming":"WY"};
const NAMES = Object.fromEntries(Object.entries(CODES).map(([n, c]) => [c, n]));
const SMALL = ["VT","NH","MA","RI","CT","NJ","DE","MD"];
const LABEL_SHIFT = { LA: [-10, 0], FL: [14, 6], MI: [12, 22], KY: [4, 2], WV: [-2, 4], ID: [0, 14], HI: [10, 8], AK: [0, 0], NY: [6, 0], CA: [-8, 0], ME: [2, -4], OK: [10, 0], VA: [8, 2], NC: [6, 0] };
const PARTY_NAME = { D: "Democrat", R: "Republican", I: "Independent / other", U: "Not yet known" };
const MODES = {
gov: { title: "Governors" },
sen: { title: "U.S. Senate" },
house: { title: "U.S. House" },
upper: { title: "State Senates" },
lower: { title: "State Houses" }
};
let mode = "gov";
let selected = null;
/* ---------- formatting ---------- */
const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
function fmtDate(raw) {
if (!raw) return "—";
const s = String(raw);
let m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (m) return `${MONTHS[+m[2] - 1]} ${+m[3]}, ${m[1]}`;
m = s.match(/^(\d{4})-(\d{2})$/);
if (m) return `${MONTHS[+m[2] - 1]} ${m[1]}`;
return s;
}
function esc(s) { return String(s ?? "").replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }
function partyKey(p) { return p === "D" || p === "R" || p === "I" ? p : "U"; }
function sq(p) { const k = partyKey(p); return `<span class="sq ${k}" role="img" aria-label="${PARTY_NAME[k]}" title="${PARTY_NAME[k]}"></span>`; }
const STATUS_TAG = { uncalled: "Not yet called", runoff: "Runoff", vacant: "Vacant", appointed: "Appointed", current: "Current leader" };
function tag(status) { return STATUS_TAG[status] ? `<span class="tag">${STATUS_TAG[status]}</span>` : ""; }
/* "■ 3D ■ 2R ■ 1I", zero counts left out */
function summary(counts, extra) {
const parts = [];
for (const k of ["D", "R", "I"]) if (counts[k] > 0) parts.push(`<span class="item">${sq(k)}${counts[k]}${k}</span>`);
if (counts.U > 0) parts.push(`<span class="item">${sq("U")}${counts.U} ${isElection() ? "not yet called" : "vacant or unknown"}</span>`);
if (extra) parts.push(`<span class="extra">${extra}</span>`);
return `<div class="sum">${parts.join("") || '<span class="extra">No data</span>'}</div>`;
}
function countParties(list) {
const c = { D: 0, R: 0, I: 0, U: 0 };
for (const p of list) c[partyKey(p)]++;
return c;
}
/* a race not yet called counts as unknown, whoever leads */
function eff(p) { return p && (p.status === "uncalled" || p.status === "runoff") ? null : p && p.party; }
/* ---------- per-state values for map coloring ---------- */
function chamber(code, which) { const l = DATA[code] && DATA[code].leg; return l ? l[which] : null; }
function chamberCounts(ch) { return { D: ch.D || 0, R: ch.R || 0, I: ch.I || 0, U: ch.uncalled || 0 }; }
function majority(c) {
const seats = c.D + c.R + c.I + c.U;
const top = ["D", "R", "I"].sort((a, b) => c[b] - c[a]);
if (!seats || c[top[0]] === c[top[1]]) return { party: null, share: 0 };
return { party: top[0], share: c[top[0]] / seats };
}
function tint(p, share) {
// share 0.5 → light tint, 1.0 → full color
const pct = Math.round(40 + Math.min(1, Math.max(0, (share - 0.5) / 0.4)) * 60);
const v = p === "D" ? "--dem" : p === "R" ? "--rep" : "--ind";
return `color-mix(in srgb, var(${v}) ${pct}%, var(--map-empty))`;
}
function fillFor(code) {
const d = DATA[code];
if (!d) return "url(#p-unk)";
if (mode === "gov") {
const k = partyKey(eff(d.gov));
return k === "U" ? "url(#p-unk)" : `var(${k === "D" ? "--dem" : k === "R" ? "--rep" : "--ind"})`;
}
if (mode === "sen") {
const ps = (d.senators || []).map(s => partyKey(eff(s)));
if (ps.includes("U")) return "url(#p-unk)";
if (ps[0] === ps[1]) return `var(${ps[0] === "D" ? "--dem" : ps[0] === "R" ? "--rep" : "--ind"})`;
if (ps.includes("I") ) return `color-mix(in srgb, var(--ind) 65%, var(${ps.includes("D") ? "--dem" : "--rep"}))`;
return "url(#p-split)";
}
let c;
if (mode === "house") c = countParties((d.house || []).map(eff));
else { const ch = chamber(code, mode); if (!ch) return "url(#p-unk)"; c = chamberCounts(ch); }
const m = majority(c);
return m.party ? tint(m.party, m.share) : "url(#p-unk)";
}
function lightLabel(code) {
// labels are white on strong fills, dark on pale tints / patterns
const f = fillFor(code);
if (f.startsWith("url")) return false;
const m = f.match(/ (\d+)%/);
return !m || +m[1] >= 70;
}
/* ---------- map (built once the shapes are loaded) ---------- */
function startMap() {
const svg = d3.select("#map");
const gStates = d3.select("#states"), gLabels = d3.select("#labels"), gChips = d3.select("#chips");
const path = d3.geoPath();
const features = topojson.feature(GEO, GEO.objects.states).features.filter(f => CODES[f.properties.name]);
features.forEach(f => { f.code = CODES[f.properties.name]; });
const tip = document.getElementById("tip");
function tipText(code) {
const d = DATA[code]; if (!d) return NAMES[code];
const g = d.gov ? `Gov. ${d.gov.name || "?"} (${partyKey(d.gov.party)})` : "";
const s = countParties((d.senators || []).map(eff));
const h = countParties((d.house || []).map(eff));
const fmt = c => ["D","R","I"].filter(k => c[k]).map(k => c[k] + k).concat(c.U ? [c.U + "?"] : []).join(" ");
return `<strong>${NAMES[code]}</strong><br>${esc(g)}<br>Senate ${fmt(s)} · House ${fmt(h)}`;
}
function showTip(ev, code) { tip.innerHTML = tipText(code); tip.hidden = false; moveTip(ev); }
function moveTip(ev) { tip.style.left = Math.min(window.innerWidth - 270, ev.clientX + 14) + "px"; tip.style.top = (ev.clientY + 14) + "px"; }
function hideTip() { tip.hidden = true; }
gStates.selectAll("path").data(features).join("path")
.attr("class", "state").attr("d", path)
.attr("tabindex", 0).attr("role", "button")
.attr("aria-label", f => NAMES[f.code])
.on("click", (ev, f) => select(f.code))
.on("keydown", (ev, f) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); select(f.code); } })
.on("mouseenter", (ev, f) => showTip(ev, f.code))
.on("mousemove", moveTip)
.on("mouseleave", hideTip);
gLabels.selectAll("text").data(features.filter(f => !SMALL.includes(f.code))).join("text")
.attr("class", "lbl")
.attr("x", f => path.centroid(f)[0] + (LABEL_SHIFT[f.code] || [0, 0])[0])
.attr("y", f => path.centroid(f)[1] + (LABEL_SHIFT[f.code] || [0, 0])[1])
.text(f => f.code);
const chip = gChips.selectAll("g").data(SMALL).join("g")
.attr("class", "chip").attr("tabindex", 0).attr("role", "button").attr("aria-label", c => NAMES[c])
.attr("transform", (c, i) => `translate(985, ${250 + i * 30})`)
.on("click", (ev, c) => select(c))
.on("keydown", (ev, c) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); select(c); } })
.on("mouseenter", (ev, c) => showTip(ev, c)).on("mousemove", moveTip).on("mouseleave", hideTip);
chip.append("rect").attr("width", 40).attr("height", 22).attr("rx", 4);
chip.append("text").attr("class", "lbl").attr("x", 20).attr("y", 11).text(c => c);
/* ---------- national totals per mode ---------- */
function nationalTotals() {
const codes = Object.keys(NAMES);
if (mode === "gov") return { title: "Governors", c: countParties(codes.map(c => eff(DATA[c]?.gov))) };
if (mode === "sen") return { title: "U.S. senators", c: countParties(codes.flatMap(c => (DATA[c]?.senators || []).map(eff))) };
if (mode === "house") return { title: "U.S. representatives", c: countParties(codes.flatMap(c => (DATA[c]?.house || []).map(eff))) };
const ctrl = { D: 0, R: 0, I: 0, U: 0 }, seats = { D: 0, R: 0, I: 0, U: 0 };
for (const c of codes) {
const ch = chamber(c, mode); if (!ch) continue;
const cc = chamberCounts(ch); for (const k in seats) seats[k] += cc[k];
const m = majority(cc); ctrl[m.party || "U"]++;
}
return { title: mode === "upper" ? "State senate chambers controlled" : "State house chambers controlled", c: ctrl, seats };
}
function renderTotals() {
const t = nationalTotals();
let html = `<span class="t-title">${t.title}</span>${summary(t.c)}`;
if (t.seats) {
const s = t.seats;
html += `<span class="t-sub">Seats: ${["D","R","I"].filter(k => s[k]).map(k => s[k].toLocaleString("en-US") + k).join(" · ")}${s.U ? " · " + s.U + " not yet called" : ""}${mode === "upper" ? " (Nebraska's unicameral legislature counted here)" : " (Nebraska has no lower house)"}</span>`;
}
document.getElementById("totals").innerHTML = html;
}
function renderLegend() {
const sw = (bg) => `<span class="sw" style="background:${bg}"></span>`;
const items = [];
if (mode === "gov" || mode === "sen") {
items.push(sw("var(--dem)") + "Democrat", sw("var(--rep)") + "Republican", sw("var(--ind)") + "Independent / other");
if (mode === "sen") items.push(sw("repeating-linear-gradient(45deg,var(--dem) 0 4px,var(--rep) 4px 8px)") + "Split delegation");
} else {
items.push(sw(tint("D", 0.95)) + "Strong D majority", sw(tint("D", 0.55)) + "Narrow D", sw(tint("R", 0.55)) + "Narrow R", sw(tint("R", 0.95)) + "Strong R majority");
}
items.push(sw("repeating-linear-gradient(45deg,var(--unk) 0 2px,var(--map-empty) 2px 6px)") + (isElection() ? (mode === "lower" ? "Tied, not yet called, or no chamber" : "Tied or not yet called") : (mode === "lower" ? "Tied, vacant, or no chamber" : "Tied or vacant")));
document.getElementById("legend").innerHTML = items.map(i => `<span>${i}</span>`).join("");
}
function paint() {
gStates.selectAll("path").style("fill", f => fillFor(f.code)).classed("sel", f => f.code === selected);
gLabels.selectAll("text").classed("dark", f => !lightLabel(f.code));
chip.select("rect").style("fill", c => fillFor(c));
chip.select("text").classed("dark", c => !lightLabel(c));
chip.classed("sel", c => c === selected);
renderTotals(); renderLegend();
}
/* ---------- detail panel ---------- */
function personRow(p, extra) {
const note = p.note ? `<span class="note">${esc(p.note)}</span>` : "";
const open = eff(p) == null;
const who = p.name ? esc(p.name) + (open && p.party ? ` (${p.party})` : "") : "Not yet known";
return `<li>${sq(eff(p))}<span class="who">${extra || ""}${who}${tag(p.status)}${note}</span><span class="end">${fmtDate(p.termEnd)}</span></li>`;
}
function chamberBlock(title, ch, code) {
if (!ch) return `<div class="cat"><h3>${title}</h3><p class="chamber">${code === "NE" ? "Nebraska has a single-chamber legislature, shown under State senators." : "No data."}</p></div>`;
const L = ch.leader;
const leader = L ? `<ul class="people">${personRow(L, `<span class="role">${esc(L.title || "Leader")}</span>`)}</ul>` : "";
const extras = [];
if (ch.vacant) extras.push(`${ch.vacant} vacant`);
if (ch.seats) extras.push(`${ch.seats} seats`);
const cnote = ch.compositionNote ? `<span class="note">${esc(ch.compositionNote)}</span>` : "";
return `<div class="cat"><h3>${title}</h3><span class="chamber">${esc(ch.name || "")}</span>${leader}${summary(chamberCounts(ch), extras.join(" · "))}${cnote}</div>`;
}
function renderState(code) {
const d = DATA[code] || {};
const sen = d.senators || [], house = (d.house || []).slice().sort((a, b) => a.district - b.district), g = d.gov;
const senHtml = `<div class="cat"><h3>U.S. senators</h3><ul class="people">${sen.map(s => personRow(s)).join("")}</ul>${summary(countParties(sen.map(eff)))}</div>`;
const houseHtml = `<div class="cat"><h3>U.S. representatives</h3><ul class="people">${house.map(r => personRow(r, `<span class="dist">${r.district === 0 ? "At-large" : "District " + r.district}</span>`)).join("")}</ul>${summary(countParties(house.map(eff)))}</div>`;
const upper = chamberBlock(code === "NE" ? "State senators (unicameral)" : "State senators", chamber(code, "upper"), code);
const lower = chamberBlock("State representatives", chamber(code, "lower"), code);
let govHtml = "";
if (g) {
const powers = (g.powers || []).length ? `<div class="chamber">Main powers</div><ul class="powers">${g.powers.map(p => `<li>${esc(p)}</li>`).join("")}</ul>` : "";
govHtml = `<div class="cat"><h3>Governor</h3><ul class="people">${personRow(g)}</ul>${summary(countParties([eff(g)]))}${powers}</div>`;
}
document.getElementById("panel").innerHTML =
`<h2>${NAMES[code]}</h2><p class="sub">${periodText()} · right-hand column = end of term</p>${senHtml}${houseHtml}${upper}${lower}${govHtml}`;
}
function renderOverview() {
const codes = Object.keys(NAMES);
const row = (label, c, extra) => `<div class="row"><span>${label}${extra ? `<span class="note">${extra}</span>` : ""}</span>${summary(c)}</div>`;
const ctrl = (which) => { const c = { D: 0, R: 0, I: 0, U: 0 }; for (const k of codes) { const ch = chamber(k, which); if (ch) c[majority(chamberCounts(ch)).party || "U"]++; } return c; };
document.getElementById("panel").innerHTML = `<h2>United States</h2><p class="sub">National totals ${fromWhen()}. Pick a state on the map for names and term ends.</p>
<div class="overview">
${row("U.S. senators", countParties(codes.flatMap(c => (DATA[c]?.senators || []).map(eff))))}
${row("U.S. representatives", countParties(codes.flatMap(c => (DATA[c]?.house || []).map(eff))))}
${row("State senates", ctrl("upper"), "Chambers by majority party, Nebraska included")}
${row("State houses", ctrl("lower"), "Chambers by majority party; 49 states")}
${row("Governors", countParties(codes.map(c => eff(DATA[c]?.gov))))}
</div>
<p class="hint">"Not yet called" counts races Wikipedia had not settled when the data was read; ties count there too for chambers.</p>`;
}
function select(code) {
selected = code && NAMES[code] ? code : null;
document.getElementById("statePick").value = selected || "";
if (selected) renderState(selected); else renderOverview();
paint();
try { history.replaceState(null, "", selected ? "#" + selected : location.pathname + location.search); } catch (e) {}
}
/* ---------- wiring ---------- */
const pick = document.getElementById("statePick");
Object.keys(NAMES).sort((a, b) => NAMES[a].localeCompare(NAMES[b])).forEach(c => pick.add(new Option(NAMES[c], c)));
pick.addEventListener("change", () => select(pick.value));
document.querySelectorAll(".modes button").forEach(b => b.addEventListener("click", () => {
mode = b.dataset.mode;
document.querySelectorAll(".modes button").forEach(x => x.setAttribute("aria-pressed", String(x === b)));
paint();
}));
window.addEventListener("hashchange", () => select(location.hash.slice(1)));
select(location.hash.slice(1));
return { rerender: () => select(selected) };
}
/* ---------- loading and updating ---------- */
async function getJSON(url, opts) {
const r = await fetch(url, Object.assign({ cache: "no-store" }, opts || {}));
let body = null;
try { body = await r.json(); } catch (e) { /* not JSON */ }
if (!r.ok && r.status !== 409) throw new Error((body && body.error) || `the server answered ${r.status}`);
return { status: r.status, body };
}
async function loadData() {
const { body } = await getJSON("/api/data");
DATA = body.data; META = body.meta;
applyMeta();
}
function setStatus(kind, html) {
const el = document.getElementById("upStatus");
el.className = "upstatus" + (kind ? " " + kind : "");
el.innerHTML = html;
el.hidden = !html;
}
function showWarnings(list, when) {
const box = document.getElementById("warnBox");
box.hidden = !list.length;
document.getElementById("warnSummary").textContent = `${list.length} warning${list.length === 1 ? "" : "s"} ${when}`;
document.getElementById("warnList").innerHTML = list.map(w => `<li>${esc(w)}</li>`).join("");
}
const btn = document.getElementById("updateBtn");
let polling = null;
function busy(on) { btn.disabled = on; btn.textContent = on ? "Updating…" : "Update from Wikipedia"; }
async function poll() {
let st;
try { st = (await getJSON("/api/update/status")).body; }
catch (e) { setStatus("error", `Could not reach the server to follow the update (${esc(e.message)}). Reload the page to try again.`); stopPolling(); return; }
if (st.state === "running") {
const last = st.messages && st.messages.length ? st.messages[st.messages.length - 1] : (st.runningElsewhere ? "An update started from the command line is running." : "Starting…");
setStatus("", `<span class="spin" aria-hidden="true"></span>${esc(last)}`);
return;
}
stopPolling();
if (st.state === "failed") {
setStatus("error", `The update did not finish: ${esc(st.error || "unknown error")}`);
return;
}
try {
await loadData();
if (app) app.rerender();
const n = (st.warnings || []).length;
setStatus("ok", n ? `Updated. Some data could not be refreshed and was kept as before (${n} warning${n === 1 ? "" : "s"} below).` : "Updated from Wikipedia. Everything was refreshed.");
} catch (e) {
setStatus("error", `The update finished, but the new data could not be loaded (${esc(e.message)}).`);
}
}
function startPolling() { busy(true); if (!polling) { polling = setInterval(poll, 1500); poll(); } }
function stopPolling() { clearInterval(polling); polling = null; busy(false); }
btn.addEventListener("click", async () => {
busy(true);
setStatus("", `<span class="spin" aria-hidden="true"></span>Starting the update…`);
try {
const { status } = await getJSON("/api/update", { method: "POST", headers: { "X-Requested-With": "us-officeholders-map" } });
if (status === 409) setStatus("", `<span class="spin" aria-hidden="true"></span>An update is already running; following it.`);
startPolling();
} catch (e) {
busy(false);
setStatus("error", `Could not start the update: ${esc(e.message)}.`);
}
});
(async function boot() {
try {
const shapes = fetch("/static/states-albers-10m.json").then(r => { if (!r.ok) throw new Error("the map shapes are missing"); return r.json(); });
const [geo] = await Promise.all([shapes, loadData()]);
GEO = geo;
app = startMap();
} catch (e) {
document.getElementById("lede").textContent = "";
document.getElementById("panel").innerHTML = `<p>The map could not be loaded: ${esc(e.message)}. Check that the server is running, then reload the page.</p>`;
return;
}
try { const st = (await getJSON("/api/update/status")).body; if (st.state === "running") startPolling(); } catch (e) { /* the map still works */ }
})();
</script>
+1
View File
@@ -0,0 +1 @@
{"type":"Topology","bbox":[-57.66491068874468,12.97635452036684,957.5235629133763,606.5694262668667],"transform":{"scale":[0.010151986255883769,0.005935990077365771],"translate":[-57.66491068874468,12.97635452036684]},"objects":{"states":{"type":"GeometryCollection","geometries":[{"type":"MultiPolygon","arcs":[[[0]],[[1,2,3,4,5]]],"id":"01","properties":{"name":"Alabama"}},{"type":"MultiPolygon","arcs":[[[6]],[[7]],[[8]],[[9]],[[10]],[[11]],[[12]],[[13]],[[14]],[[15]],[[16]],[[17]],[[18]],[[19]],[[20]],[[21]],[[22]],[[23]],[[24]],[[25]],[[26]],[[27]],[[28]],[[29]],[[30]],[[31]],[[32]],[[33]],[[34]],[[35]],[[36]],[[37]],[[38]],[[39]],[[40]],[[41]],[[42]],[[43]],[[44]],[[45]],[[46]],[[47]],[[48]],[[49]],[[50]],[[51]],[[52]],[[53]],[[54]],[[55]],[[56]],[[57]],[[58]],[[59]],[[60]],[[61]]],"id":"02","properties":{"name":"Alaska"}},{"type":"Polygon","arcs":[[62,63,64,65,66]],"id":"04","properties":{"name":"Arizona"}},{"type":"Polygon","arcs":[[67,68,69,70,71,72]],"id":"08","properties":{"name":"Colorado"}},{"type":"MultiPolygon","arcs":[[[73]],[[74]],[[75]],[[76]],[[77]],[[78]],[[79]],[[80]],[[81]],[[82,83,-4]]],"id":"12","properties":{"name":"Florida"}},{"type":"Polygon","arcs":[[84,85,86,87,-83,-3]],"id":"13","properties":{"name":"Georgia"}},{"type":"Polygon","arcs":[[88,89,90,91,92]],"id":"18","properties":{"name":"Indiana"}},{"type":"Polygon","arcs":[[93,94,95,-70]],"id":"20","properties":{"name":"Kansas"}},{"type":"MultiPolygon","arcs":[[[96]],[[97]],[[98]],[[99]],[[100]],[[101]],[[102]],[[103,104]]],"id":"23","properties":{"name":"Maine"}},{"type":"MultiPolygon","arcs":[[[105]],[[106]],[[107,108,109,110,111,112,113,114]]],"id":"25","properties":{"name":"Massachusetts"}},{"type":"Polygon","arcs":[[115,116,117,118,119]],"id":"27","properties":{"name":"Minnesota"}},{"type":"Polygon","arcs":[[120,121,122,123,124,125,126,127]],"id":"34","properties":{"name":"New Jersey"}},{"type":"MultiPolygon","arcs":[[[128]],[[129]],[[130,131,132,-86,133]]],"id":"37","properties":{"name":"North Carolina"}},{"type":"Polygon","arcs":[[134,-120,135,136]],"id":"38","properties":{"name":"North Dakota"}},{"type":"Polygon","arcs":[[-71,-96,137,138,139,140]],"id":"40","properties":{"name":"Oklahoma"}},{"type":"Polygon","arcs":[[141,142,-123,143,144,145,146]],"id":"42","properties":{"name":"Pennsylvania"}},{"type":"Polygon","arcs":[[147,-136,-119,148,149,150]],"id":"46","properties":{"name":"South Dakota"}},{"type":"Polygon","arcs":[[-140,151,152,153,154]],"id":"48","properties":{"name":"Texas"}},{"type":"Polygon","arcs":[[-151,155,-68,156,157,158]],"id":"56","properties":{"name":"Wyoming"}},{"type":"Polygon","arcs":[[-114,159,160,161]],"id":"09","properties":{"name":"Connecticut"}},{"type":"Polygon","arcs":[[162,163,164,165,166,167,168,-138,-95,169]],"id":"29","properties":{"name":"Missouri"}},{"type":"Polygon","arcs":[[170,-146,171,172,173]],"id":"54","properties":{"name":"West Virginia"}},{"type":"Polygon","arcs":[[174,175,176,-93,177,-164]],"id":"17","properties":{"name":"Illinois"}},{"type":"Polygon","arcs":[[-72,-141,-155,178,-66]],"id":"35","properties":{"name":"New Mexico"}},{"type":"Polygon","arcs":[[-169,179,180,181,-152,-139]],"id":"05","properties":{"name":"Arkansas"}},{"type":"MultiPolygon","arcs":[[[182]],[[183]],[[184]],[[185]],[[186]],[[187]],[[188]],[[189,190,-63,191]]],"id":"06","properties":{"name":"California"}},{"type":"MultiPolygon","arcs":[[[-128,192]],[[-144,-122,193,194]]],"id":"10","properties":{"name":"Delaware"}},{"type":"Polygon","arcs":[[195,196]],"id":"11","properties":{"name":"District of Columbia"}},{"type":"MultiPolygon","arcs":[[[197]],[[198]],[[199]],[[200]],[[201]],[[202]],[[203]],[[204]]],"id":"15","properties":{"name":"Hawaii"}},{"type":"Polygon","arcs":[[-118,205,-175,-163,206,-149]],"id":"19","properties":{"name":"Iowa"}},{"type":"MultiPolygon","arcs":[[[-178,-92,207,-174,208,209,-165]],[[210,-167]]],"id":"21","properties":{"name":"Kentucky"}},{"type":"MultiPolygon","arcs":[[[211,212]],[[213]],[[-145,-195,214,215,216,217,-196,218,-172]]],"id":"24","properties":{"name":"Maryland"}},{"type":"MultiPolygon","arcs":[[[219]],[[220]],[[221]],[[222]],[[223]],[[224]],[[225]],[[226]],[[227,228,-90]],[[229]],[[230,231]]],"id":"26","properties":{"name":"Michigan"}},{"type":"MultiPolygon","arcs":[[[232]],[[233]],[[234]],[[235]],[[-181,236,-6,237,238]]],"id":"28","properties":{"name":"Mississippi"}},{"type":"Polygon","arcs":[[239,-137,-148,-159,240]],"id":"30","properties":{"name":"Montana"}},{"type":"Polygon","arcs":[[241,-104,242,-109,243]],"id":"33","properties":{"name":"New Hampshire"}},{"type":"MultiPolygon","arcs":[[[244]],[[245]],[[246,-126]],[[247]],[[248]],[[249,250,-115,-162,251,-124,-143]]],"id":"36","properties":{"name":"New York"}},{"type":"MultiPolygon","arcs":[[[252]],[[253]],[[-229,254,-147,-171,-208,-91]]],"id":"39","properties":{"name":"Ohio"}},{"type":"Polygon","arcs":[[255,256,257,-190,258]],"id":"41","properties":{"name":"Oregon"}},{"type":"Polygon","arcs":[[-168,-211,-166,-210,259,-134,Line truncated
+379
View File
@@ -0,0 +1,379 @@
"""Refresh the map data from English Wikipedia.
Usage (inside the container): python update.py
Mode: UPDATE_MODE=auto|election|current (auto = election results between Election Day and January 3, else current officeholders).
Each category (senate, house, governors, legislatures) is checked before it replaces the stored file;
if reading or checking fails, the previous data for that category is kept and a warning is recorded.
"""
import datetime as dt
import json
import os
import sys
import time
import traceback
import common as C
import parsers as P
from wiki import Client, WikiError
LOCK = ".update.lock"
LOCK_STALE_SECONDS = 300 # the running update touches the lock at every step, so an older lock is left over from a crash
class Busy(Exception):
pass
def acquire_lock():
C.ensure_dir()
p = C.path(LOCK)
try:
fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
try:
age = time.time() - os.path.getmtime(p)
except OSError:
age = 0
if age < LOCK_STALE_SECONDS:
raise Busy("An update is already running.")
os.unlink(p)
fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
with os.fdopen(fd, "w") as f:
f.write(f"{os.getpid()} {dt.datetime.now(dt.timezone.utc).isoformat()}\n")
def release_lock():
try:
os.unlink(C.path(LOCK))
except OSError:
pass
def lock_held():
p = C.path(LOCK)
return os.path.exists(p) and time.time() - os.path.getmtime(p) < LOCK_STALE_SECONDS
# ---------------------------------------------------------------- validation
def validate_senate(data):
errs = []
if len(data) != 50 or set(data) != set(C.NAMES):
errs.append(f"{len(data)} states instead of 50")
total = sum(len(v) for v in data.values())
if total != 100:
errs.append(f"{total} senators instead of 100")
for code, v in sorted(data.items()):
if len(v) != 2:
errs.append(f"{C.NAMES.get(code, code)} has {len(v)} senators")
elif v[0]["class"] == v[1]["class"]:
errs.append(f"{C.NAMES[code]} has two class {v[0]['class']} senators")
for s in v:
if not s["name"] and s["status"] not in ("uncalled", "runoff", "vacant"):
errs.append(f"a {C.NAMES.get(code, code)} senator has no name")
if s["name"] and s["party"] not in ("D", "R", "I"):
errs.append(f"no party for {s['name']}")
return errs
def validate_house(data):
errs = []
if set(data) != set(C.NAMES):
missing = sorted(set(C.NAMES) - set(data))
errs.append(f"{len(data)} states instead of 50" + (f" (missing {', '.join(missing[:5])})" if missing else ""))
total = sum(len(v) for v in data.values())
if total != 435:
errs.append(f"{total} representatives instead of 435")
for code, n in C.APPORTIONMENT.items():
v = data.get(code, [])
if len(v) != n:
errs.append(f"{C.NAMES[code]}: {len(v)} seats instead of {n}")
continue
expected = [0] if n == 1 else list(range(1, n + 1))
if sorted(r["district"] for r in v) != expected and not (n == 1 and [r["district"] for r in v] == [1]):
errs.append(f"{C.NAMES[code]}: unexpected district numbers")
for r in v:
if r["name"] and r["party"] not in ("D", "R", "I"):
errs.append(f"no party for {r['name']}")
if not r["name"] and r["status"] not in ("uncalled", "runoff", "vacant"):
errs.append(f"{C.NAMES[code]} district {r['district']} has no name")
return errs
def validate_governors(data):
errs = []
if set(data) != set(C.NAMES):
errs.append(f"{len(data)} governors instead of 50")
for code, g in data.items():
if not g["name"] and g["status"] not in ("uncalled", "runoff", "vacant"):
errs.append(f"no governor name for {C.NAMES.get(code, code)}")
if g["name"] and g["party"] not in ("D", "R", "I"):
errs.append(f"no party for governor {g['name']}")
return errs
def chamber_errors(code, which, ch):
size = C.CHAMBERS[code][0 if which == "upper" else 1][1]
total = ch["D"] + ch["R"] + ch["I"] + ch["vacant"] + ch["uncalled"]
if ch["seats"] != size or total != size:
return f"seats add up to {total} instead of {size}"
return None
def validate_legislatures(data):
errs = []
if set(data) != set(C.NAMES):
errs.append(f"{len(data)} states instead of 50")
n = 0
for code, legs in data.items():
for which in ("upper", "lower"):
ch = legs.get(which)
if ch is None:
if not (code == "NE" and which == "lower"):
errs.append(f"{C.NAMES[code]} {which} chamber missing")
continue
n += 1
e = chamber_errors(code, which, ch)
if e:
errs.append(f"{ch['name']}: {e}")
if n != 99:
errs.append(f"{n} chambers instead of 99")
return errs
VALIDATORS = {"senate": validate_senate, "house": validate_house, "governors": validate_governors,
"legislatures": validate_legislatures}
LABEL = {"senate": "U.S. Senate", "house": "U.S. House", "governors": "Governors", "legislatures": "State legislatures"}
# ---------------------------------------------------------------- totals (for messages and the CLI)
def party_totals(entries):
t = {"D": 0, "R": 0, "I": 0, "unknown": 0}
for e in entries:
if not e or e.get("status") in ("uncalled", "runoff") or e.get("party") not in ("D", "R", "I"):
t["unknown"] += 1
else:
t[e["party"]] += 1
return t
def totals(cat, data):
if cat == "senate":
return party_totals([s for v in data.values() for s in v])
if cat == "house":
return party_totals([r for v in data.values() for r in v])
if cat == "governors":
return party_totals(list(data.values()))
seats = {"D": 0, "R": 0, "I": 0, "vacant": 0, "uncalled": 0, "chambers": 0}
for legs in data.values():
for ch in legs.values():
if ch:
seats["chambers"] += 1
for k in ("D", "R", "I", "vacant", "uncalled"):
seats[k] += ch[k]
return seats
def fmt_totals(t):
return ", ".join(f"{v} {k}" for k, v in t.items() if v)
# ---------------------------------------------------------------- the run
def now_iso():
return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
def run_update(progress=print, requested_mode=None):
"""Run a full update. Returns a summary dict. Raises Busy if another update holds the lock."""
C.ensure_seed()
acquire_lock()
def progress_and_touch(msg):
try:
os.utime(C.path(LOCK))
except OSError:
pass
progress(msg)
try:
return _run(progress_and_touch, requested_mode)
finally:
release_lock()
def _run(progress, requested_mode):
day = C.today()
mode, requested = C.choose_mode(day, requested_mode)
year = C.election_window(day) or C.last_election_year(day)
started = now_iso()
warnings, results = [], {}
client = Client(progress)
progress(f"Mode: {'election results ' + str(year) if mode == 'election' else 'current officeholders'}"
f"{' (forced by UPDATE_MODE)' if requested != 'auto' else ' (chosen from today’s date)'}")
def attempt(cat, fn):
progress(f"{LABEL[cat]}: reading Wikipedia…")
try:
data, sources = fn()
except (P.ParseError, WikiError, KeyError, ValueError, IndexError, StopIteration) as e:
warnings.append(f"{LABEL[cat]}: kept the previous data because Wikipedia could not be read as expected ({e}).")
progress(f"{LABEL[cat]}: failed, previous data kept")
traceback.print_exc(file=sys.stderr)
return None
errs = VALIDATORS[cat](data)
if errs:
more = f" and {len(errs) - 4} more problem(s)" if len(errs) > 4 else ""
warnings.append(f"{LABEL[cat]}: kept the previous data because the new data did not pass the checks: "
f"{'; '.join(errs[:4])}{more}.")
progress(f"{LABEL[cat]}: checks failed, previous data kept")
return None
return data, sources
meta_base = {"mode": mode, "electionYear": year if mode == "election" else None}
# Governors first: the Senate step uses them to flag senators who were elected governor.
if mode == "election":
g = attempt("governors", lambda: P.governors_election(client, year))
else:
g = attempt("governors", lambda: P.governors_current(client, day))
if g:
save("governors", g[0], g[1], meta_base, progress, results)
if mode == "election":
s = attempt("senate", lambda: P.senate_election(client, year))
else:
s = attempt("senate", lambda: P.senate_current(client, day))
if s:
if mode == "election" and g:
flag_senators_elected_governor(s[0], g[0], year)
save("senate", s[0], s[1], meta_base, progress, results)
if mode == "election":
h = attempt("house", lambda: P.house_election(client, year))
else:
h = attempt("house", lambda: P.house_current(client, day))
if h:
save("house", h[0], h[1], meta_base, progress, results)
update_legislatures(client, mode, day, year, meta_base, progress, warnings, results)
finished = now_iso()
run = {"startedAt": started, "finishedAt": finished, "mode": mode, "requestedMode": requested,
"electionYear": meta_base["electionYear"], "updated": sorted(results), "warnings": warnings,
"requests": client.requests}
meta = C.read_json(C.path("meta.json"), {}) or {}
meta["lastRun"] = run
C.write_json_atomic(C.path("meta.json"), meta)
run["totals"] = {cat: fmt_totals(t) for cat, t in results.items()}
progress(f"Done: {len(results)} of 4 categories updated, {len(warnings)} warning(s).")
return run
def save(cat, data, sources, meta_base, progress, results):
meta = dict(meta_base, asOf=now_iso(), sources=sources)
C.save_category(cat, data, meta)
results[cat] = totals(cat, data)
progress(f"{LABEL[cat]}: updated ({fmt_totals(results[cat])})")
def flag_senators_elected_governor(senate, governors, year):
for code, sens in senate.items():
g = governors.get(code)
if not g or g.get("status") != f"elected-{year}" or not g.get("name"):
continue
for s in sens:
if s["status"] == "continuing" and s["name"] and s["name"].lower() == g["name"].lower():
s["note"] = (f"Elected Governor of {C.NAMES[code]} in {year}; the Senate seat will be filled "
f"after the new governor takes office. " + s["note"]).strip()
def update_legislatures(client, mode, day, year, meta_base, progress, warnings, results):
cat = "legislatures"
progress(f"{LABEL[cat]}: reading Wikipedia…")
try:
data, sources, problems = P.legislatures(client, mode, day, year)
except (P.ParseError, WikiError, KeyError, ValueError, IndexError) as e:
warnings.append(f"{LABEL[cat]}: kept the previous data because Wikipedia could not be read as expected ({e}).")
traceback.print_exc(file=sys.stderr)
return
prev_file = C.load_category(cat) or {}
prev = prev_file.get("data", {})
def same_cycle(meta):
meta = meta or {}
return meta.get("mode") == mode and (mode != "election" or meta.get("electionYear") == year)
# Earlier figures for the same election (stored data first, then the seed shipped with the app):
# used while Wikipedia has no post-election figures yet for a chamber.
earlier = [f.get("data", {}) for f in (prev_file, C.read_json(os.path.join(C.SEED_DIR, cat + ".json"), {}) or {})
if f and same_cycle(f.get("meta"))]
kept, unknown_kept = [], []
for code, legs in data.items():
for which in ("upper", "lower"):
ch = legs.get(which)
if ch is None:
continue
reason = problems.get((code, which)) or chamber_errors(code, which, ch)
old = (prev.get(code) or {}).get(which)
if reason:
if old:
legs[which] = old
kept.append(f"{ch['name']} ({reason})")
else:
kept.append(f"{ch['name']} ({reason}; no previous data either)")
continue
same = [e for e in ((d.get(code) or {}).get(which) for d in earlier) if e]
if ch.pop("_unknown", False):
better = [e for e in same if e.get("uncalled", 0) < ch["uncalled"]]
if better:
# Wikipedia has no post-election figures yet: keep the earlier, more complete figures.
legs[which] = better[0]
unknown_kept.append(ch["name"])
continue
named = [e["leader"] for e in same if (e.get("leader") or {}).get("name") and e["leader"].get("status") != "current"]
if mode == "election" and named and (ch.get("leader") or {}).get("status") == "current":
# an earlier read recorded the leader chosen for the new session: better than the outgoing one
ch["leader"] = named[0]
for legs in data.values():
for ch in legs.values():
if ch:
ch.pop("_unknown", None)
if len(kept) > 20:
warnings.append(f"{LABEL[cat]}: kept all previous data because {len(kept)} chambers could not be read "
f"(for example {'; '.join(kept[:3])}).")
return
errs = validate_legislatures(data)
if errs:
warnings.append(f"{LABEL[cat]}: kept the previous data because the new data did not pass the checks: {'; '.join(errs[:4])}.")
return
if kept:
warnings.append(f"{LABEL[cat]}: previous figures kept for {len(kept)} chamber(s) whose Wikipedia data did not add up: "
+ "; ".join(kept) + ".")
if unknown_kept:
warnings.append(f"{LABEL[cat]}: Wikipedia has no {year} results yet for {len(unknown_kept)} chamber(s); "
f"the earlier figures were kept: {', '.join(unknown_kept)}.")
save(cat, data, sources, meta_base, progress, results)
def main():
try:
run = run_update(progress=lambda m: print(m, flush=True))
except Busy as e:
print(str(e))
return 2
print()
print("Totals:")
for cat, t in run["totals"].items():
print(f" {LABEL[cat]}: {t}")
if run["warnings"]:
print("Warnings:")
for w in run["warnings"]:
print(" - " + w)
return 0
if __name__ == "__main__":
sys.exit(main())
+406
View File
@@ -0,0 +1,406 @@
"""English Wikipedia API client and small wikitext helpers (standard library only)."""
import html
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
API = "https://en.wikipedia.org/w/api.php"
USER_AGENT = "us-officeholders-map/1.0"
DELAY = float(os.environ.get("WIKI_DELAY", "1.5")) # seconds between requests
CACHE_DIR = os.environ.get("WIKI_CACHE_DIR") # development only: reuse fetched pages
class WikiError(Exception):
pass
class Client:
def __init__(self, progress=None):
self.progress = progress or (lambda msg: None)
self._last = 0.0
self.requests = 0
self.revisions = {} # title -> revision timestamp or id
def _get(self, params):
params = dict(params, format="json", formatversion="2", maxlag="5")
url = API + "?" + urllib.parse.urlencode(params)
for attempt in range(6):
wait = self._last + DELAY - time.time()
if wait > 0:
time.sleep(wait)
self._last = time.time()
self.requests += 1
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept-Encoding": "identity"})
retry_after = None
try:
with urllib.request.urlopen(req, timeout=60) as resp:
body = json.loads(resp.read().decode("utf-8"))
err = body.get("error")
if err and err.get("code") == "maxlag":
retry_after = 5
elif err:
raise WikiError(f"Wikipedia API error: {err.get('info') or err.get('code')}")
else:
return body
except urllib.error.HTTPError as e:
if e.code == 429 or e.code >= 500:
ra = e.headers.get("Retry-After")
retry_after = int(ra) if ra and ra.isdigit() else None
else:
raise WikiError(f"Wikipedia answered HTTP {e.code}") from e
except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
if attempt == 5:
raise WikiError(f"Could not reach Wikipedia ({e})") from e
delay = retry_after if retry_after is not None else min(60, 2 * 2 ** attempt)
self.progress(f"Wikipedia is busy, retrying in {delay} s…")
time.sleep(delay)
raise WikiError("Wikipedia did not answer after several attempts")
def _cache(self, title, text=None):
if not CACHE_DIR:
return None
p = os.path.join(CACHE_DIR, re.sub(r"[^\w.-]+", "_", title) + ".wiki")
if text is None:
if os.path.exists(p):
with open(p, encoding="utf-8") as f:
return f.read()
return None
os.makedirs(CACHE_DIR, exist_ok=True)
with open(p, "w", encoding="utf-8") as f:
f.write(text)
return text
def page(self, title):
"""Wikitext of one page (action=parse), following redirects."""
cached = self._cache(title)
if cached is not None:
return cached
self.progress(f"Reading “{title}”")
body = self._get({"action": "parse", "page": title, "prop": "wikitext|revid", "redirects": "1"})
p = body.get("parse") or {}
text = p.get("wikitext")
if text is None:
raise WikiError(f"No text returned for “{title}”")
self.revisions[title] = p.get("revid")
self._cache(title, text)
return text
def pages(self, titles, label="pages"):
"""Wikitext of many pages, 50 per request (action=query). Returns {requested title: text or None}."""
out = {}
todo = []
for t in titles:
c = self._cache(t)
if c is not None:
out[t] = c
else:
todo.append(t)
for i in range(0, len(todo), 50):
chunk = todo[i:i + 50]
self.progress(f"Reading {label} {i + 1}–{i + len(chunk)} of {len(todo)}")
body = self._get({"action": "query", "prop": "revisions", "rvprop": "content|ids", "rvslots": "main",
"titles": "|".join(chunk), "redirects": "1"})
q = body.get("query", {})
norm = {n["from"]: n["to"] for n in q.get("normalized", [])}
redir = {r["from"]: r["to"] for r in q.get("redirects", [])}
by_title = {p["title"]: p for p in q.get("pages", [])}
for t in chunk:
t2 = norm.get(t, t)
t2 = redir.get(t2, t2)
p = by_title.get(t2)
if not p or p.get("missing") or not p.get("revisions"):
out[t] = None
continue
rev = p["revisions"][0]
out[t] = rev["slots"]["main"]["content"]
self.revisions[t] = rev.get("revid")
self._cache(t, out[t])
return out
# ---------------------------------------------------------------- wikitext helpers
def strip_noise(text):
text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
text = re.sub(r"<ref[^>/]*/>", "", text)
text = re.sub(r"<ref[^>]*>.*?</ref>", "", text, flags=re.S)
return text
def find_template(text, name, start=0):
"""Balanced {{name ...}} starting at or after `start`; returns (start, end) or None."""
m = re.compile(r"\{\{\s*" + name, re.I).search(text, start)
if not m:
return None
i = m.start()
depth = 0
j = i
while j < len(text):
if text.startswith("{{", j):
depth += 1
j += 2
elif text.startswith("}}", j):
depth -= 1
j += 2
if depth == 0:
return i, j
else:
j += 1
return i, len(text)
def split_top(s, sep="|"):
"""Split on `sep` outside [[ ]] and {{ }}."""
parts, cur, depth, i = [], [], 0, 0
while i < len(s):
two = s[i:i + 2]
if two in ("[[", "{{"):
depth += 1
cur.append(two)
i += 2
continue
if two in ("]]", "}}") and depth > 0:
depth -= 1
cur.append(two)
i += 2
continue
if depth == 0 and s.startswith(sep, i):
parts.append("".join(cur))
cur = []
i += len(sep)
continue
cur.append(s[i])
i += 1
parts.append("".join(cur))
return parts
def template_params(tpl):
body = tpl[2:-2]
parts = split_top(body)
named, positional = {}, []
for p in parts[1:]:
if "=" in p and re.match(r"^\s*[\w ]+\s*=", p):
k, v = p.split("=", 1)
named[k.strip()] = v.strip()
else:
positional.append(p.strip())
return named, positional
def infobox(text, name="Infobox"):
loc = find_template(strip_noise(text), name)
if not loc:
return {}
t = strip_noise(text)
named, _ = template_params(t[loc[0]:loc[1]])
return named
_KEEP_FIRST = {"nowrap", "no wrap", "small", "smaller", "resize", "center", "nobold", "big", "nobr", "abbr", "lang", "notatypo", "sic", "tooltip", "h", "strong"}
def _template_plain(m):
inner = m.group(1)
parts = inner.split("|")
name = parts[0].strip().lower()
args = [p for p in parts[1:] if not re.match(r"^\s*\w+\s*=", p)]
if name == "sortname" and len(args) >= 2:
return f"{args[0].strip()} {args[1].strip()}"
if name in _KEEP_FIRST and args:
return args[0]
if name == "!":
return "|"
if name in ("dts", "start date", "birth date and age", "birth date"):
return " ".join(a.strip() for a in args[:3])
if name in ("legend", "legend0") and len(args) >= 2:
return args[1]
return ""
def plain(s):
"""Rough wikitext -> text."""
if not s:
return ""
s = strip_noise(s)
s = re.sub(r"\[\[(?:File|Image):[^\[\]]*(?:\[\[[^\]]*\]\][^\[\]]*)*\]\]", "", s, flags=re.I)
for _ in range(4):
s2 = re.sub(r"\[\[(?:[^|\]]*\|)?([^\]|]*)\]\]", r"\1", s)
s2 = re.sub(r"\{\{([^{}]*)\}\}", _template_plain, s2)
if s2 == s:
break
s = s2
s = re.sub(r"\[https?://[^\s\]]+\s*([^\]]*)\]", r"\1", s)
s = re.sub(r"'{2,}", "", s)
s = re.sub(r"<br\s*/?>", " ", s, flags=re.I)
s = re.sub(r"<[^>]+>", "", s)
s = html.unescape(s).replace(" ", " ")
return re.sub(r"\s+", " ", s).strip()
def sections(text, level=2):
"""[(heading, body)] for headings of exactly `level` (body runs to the next heading of that level or higher)."""
eq = "=" * level
pat = re.compile(r"^" + eq + r"(?!=)\s*(.+?)\s*" + eq + r"\s*$", re.M)
heads = list(pat.finditer(text))
out = []
for i, m in enumerate(heads):
end = heads[i + 1].start() if i + 1 < len(heads) else len(text)
body = text[m.end():end]
# stop at a higher-level heading
for lv in range(1, level):
hm = re.search(r"^" + "=" * lv + r"(?!=)[^=\n].*?" + "=" * lv + r"\s*$", body, re.M)
if hm:
body = body[:hm.start()]
out.append((plain(m.group(1)), body))
return out
def section(text, title, level=2):
for h, body in sections(text, level):
if h.lower() == title.lower():
return body
return None
# ---------------------------------------------------------------- tables
class Cell:
__slots__ = ("raw", "text", "header", "attrs", "rowspan", "colspan")
def __init__(self, raw, header, attrs):
self.raw = raw.strip()
self.text = plain(raw)
self.header = header
self.attrs = attrs
rs = re.search(r"rowspan\s*=\s*\"?(\d+)", attrs)
cs = re.search(r"colspan\s*=\s*\"?(\d+)", attrs)
self.rowspan = int(rs.group(1)) if rs else 1
self.colspan = int(cs.group(1)) if cs else 1
def __repr__(self):
return f"Cell({self.text!r})"
_ATTR_TEMPLATES = re.compile(r"\{\{\s*(party shading|party color|shading pvi|usraterating)[^{}]*\}\}", re.I)
def _split_attrs(cell):
parts = split_top(cell, "|")
if len(parts) >= 2:
left = _ATTR_TEMPLATES.sub(" ", parts[0])
left = re.sub(r"[\w-]+\s*=\s*(\"[^\"]*\"|'[^']*'|[^\s]+)", " ", left)
if not left.strip():
return parts[0], "|".join(parts[1:])
return "", cell
class Table:
def __init__(self, raw, start):
self.raw = raw
self.start = start
self.caption = ""
self.rows = [] # list of lists of Cell (spans expanded)
self.row_raw = []
self._parse()
def _parse(self):
lines = self.raw.split("\n")
rows, raws = [], []
cur, cur_raw = None, None
depth = 0
for ln in lines[1:]:
s = ln.strip()
if depth > 0:
if cur:
cur[-1] = (cur[-1][0] + "\n" + ln, cur[-1][1], cur[-1][2])
if s.startswith("{|"):
depth += 1
if s.startswith("|}"):
depth -= 1
continue
if s.startswith("{|"):
depth += 1
if cur:
cur[-1] = (cur[-1][0] + "\n" + ln, cur[-1][1], cur[-1][2])
continue
if s.startswith("|}"):
break
if s.startswith("|+"):
cap = s[2:]
a, content = _split_attrs(cap)
self.caption = plain(content)
continue
if s.startswith("|-"):
cur, cur_raw = [], []
rows.append(cur)
raws.append(cur_raw)
continue
if cur is None:
cur, cur_raw = [], []
rows.append(cur)
raws.append(cur_raw)
cur_raw.append(ln)
if s.startswith("!"):
for c in split_top(s[1:], "!!"):
for c2 in split_top(c, "||"):
a, content = _split_attrs(c2)
cur.append((content, True, a))
elif s.startswith("|"):
for c in split_top(s[1:], "||"):
a, content = _split_attrs(c)
cur.append((content, False, a))
elif cur:
cur[-1] = (cur[-1][0] + "\n" + ln, cur[-1][1], cur[-1][2])
grid, grid_raw, pending = [], [], {}
for r, rr in zip(rows, raws):
if not r and not pending:
continue
cells = [Cell(c, h, a) for c, h, a in r]
line, col, ci = [], 0, 0
while ci < len(cells) or col in pending:
if col in pending:
rem, c = pending[col]
line.append(c)
if rem <= 1:
del pending[col]
else:
pending[col] = (rem - 1, c)
col += 1
continue
c = cells[ci]
ci += 1
for _ in range(min(c.colspan, 50)):
line.append(c)
if c.rowspan > 1:
pending[col] = (c.rowspan - 1, c)
col += 1
if line:
grid.append(line)
grid_raw.append("\n".join(rr))
self.rows = grid
self.row_raw = grid_raw
def texts(self, i):
return [c.text for c in self.rows[i]]
def tables(text):
"""All tables (outer and nested) with their start offsets, in document order."""
out, stack = [], []
for m in re.finditer(r"^[ \t]*(\{\||\|\})", text, re.M):
if m.group(1) == "{|":
stack.append(m.start())
elif stack:
s = stack.pop()
out.append(Table(text[s:m.end()], s))
return sorted(out, key=lambda t: t.start)
def split_rows(table_text):
"""Raw row chunks of a wikitext table (split on |- lines)."""
return re.split(r"\n[ \t]*\|-[^\n]*", table_text)
+736
View File
@@ -0,0 +1,736 @@
{
"meta": {
"mode": "election",
"electionYear": 2026,
"asOf": "2026-11-13T14:34:55+00:00",
"sources": [
"2026 United States gubernatorial elections",
"List of current United States governors"
]
},
"data": {
"AL": {
"name": "Tommy Tuberville",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; legislature overrides by majority of elected members",
"Amendatory veto and line-item veto",
"Can grant clemency; fills vacancies in elected offices",
"Appoints cabinet and members of 450+ boards and commissions",
"Commander-in-chief of the militia; oversees state finances",
"Two consecutive four-year terms"
]
},
"AK": {
"name": "Jonathan Kreiss-Tomkins",
"party": "D",
"termEnd": "2030-12",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by 2/3 of legislators in joint session",
"Budget bills: override needs 3/4 of elected legislators",
"Line-item and reduction veto on appropriations",
"Commander-in-chief of Alaska's state forces",
"Two consecutive four-year terms"
]
},
"AZ": {
"name": "Katie Hobbs",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by 2/3 of elected members (3/4 for some bills)",
"Line-item veto on appropriations",
"Grants pardons, except in impeachment cases",
"Commander-in-chief of state military forces; convenes legislature",
"Two consecutive terms; may run again after four years"
]
},
"AR": {
"name": "Sarah Huckabee Sanders",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by simple majority",
"Line-item veto on appropriations bills",
"Appoints the 15 cabinet secretaries",
"Can call the General Assembly into special session",
"Commander-in-chief of the state militia",
"Limited to two four-year terms"
]
},
"CA": {
"name": "Xavier Becerra",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto on budget bills",
"Prepares and submits the annual state budget",
"Appoints state judges to vacant seats",
"Pardons and commutations, some need state Supreme Court approval",
"Commander-in-chief of National Guard; two-term limit"
]
},
"CO": {
"name": "Phil Weiser",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto on appropriations",
"Grants pardons, except for treason or impeachment",
"Commander-in-chief of state military forces",
"Two consecutive terms; eligible again after four years"
]
},
"CT": {
"name": "Ned Lamont",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"No pardon power, unusual among governors",
"Commander-in-chief of state military forces; convenes legislature",
"Four-year terms, no term limit"
]
},
"DE": {
"name": "Matt Meyer",
"party": "D",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by three-fifths of elected members",
"Line-item veto and pocket veto",
"Pardons only on recommendation of the Board of Pardons",
"Commander-in-chief of state military forces; convenes legislature",
"Limited to two terms"
]
},
"FL": {
"name": "Byron Donalds",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds of members present",
"Line-item veto on appropriations",
"Proposes and oversees the state budget",
"Grants pardons (except impeachment); key state appointments",
"Commander-in-chief of Florida National Guard and State Guard",
"Two consecutive four-year terms"
]
},
"GA": {
"name": "Keisha Lance Bottoms",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"Calls the General Assembly into special session",
"Can suspend or remove officers after a commission finding",
"Commander-in-chief of National Guard and State Defense Force",
"Two consecutive terms, then four years out"
]
},
"HI": {
"name": "Josh Green",
"party": "D",
"termEnd": "2030-12",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item and reduction veto",
"Appoints all state judges, subject to Senate approval",
"Appoints many statewide executives, e.g. attorney general",
"Commander-in-chief of Hawaii's armed forces",
"Two consecutive terms, then must sit out a term"
]
},
"ID": {
"name": "Brad Little",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item veto",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"IL": {
"name": "JB Pritzker",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"Amendatory, line-item and reduction vetoes",
"Reduction vetoes overridden by simple majority",
"Power of pardon and commutation",
"Commander-in-chief of state forces in state service",
"Four-year terms, no term limit"
]
},
"IN": {
"name": "Mike Braun",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; General Assembly overrides by simple majority",
"No line-item veto; pocket veto ruled unconstitutional",
"Pardons and commutations, except treason or impeachment",
"Appoints judges to fill vacancies",
"Can call out the Indiana National Guard in emergencies",
"Two terms in any 12-year period"
]
},
"IA": {
"name": "Rob Sand",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto and pocket veto",
"Grants pardons, except treason and impeachment",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"KS": {
"name": "Cindy Holscher",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of membership",
"Line-item veto",
"Grants pardons; can convene legislature at any time",
"Commander-in-chief of state military forces",
"Two consecutive four-year terms"
]
},
"KY": {
"name": "Andy Beshear",
"party": "D",
"termEnd": "2027-12",
"status": "continuing",
"note": "Term-limited.",
"powers": [
"Veto; General Assembly overrides by simple majority",
"Line-item veto; no pocket veto",
"Proposes the biennial state budget",
"Broad appointment power over cabinets and commissions",
"Grants pardons, except impeachment cases",
"Two consecutive terms, then four years out"
]
},
"LA": {
"name": "Jeff Landry",
"party": "R",
"termEnd": "2028-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto, required to keep the budget balanced",
"Submits operating budget and five-year capital outlay plan",
"Appoints cabinet secretaries leading state agencies",
"Pardons, reprieves, commutations; commands National Guard",
"Limited to two terms in a lifetime"
]
},
"ME": {
"name": "Hannah Pingree",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item and reduction veto",
"Appoints judges and officers, confirmed by the Legislature",
"Pardons, reprieves and commutations, except impeachment",
"Commander-in-chief of the Maine National Guard",
"Two consecutive four-year terms"
]
},
"MD": {
"name": "Wes Moore",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"Line-item veto on appropriations",
"Presents budget; legislature can cut but not increase it",
"Appoints most officers and cabinet, with Senate consent",
"Pardons and commutations; commands the National Guard",
"Two consecutive four-year terms"
]
},
"MA": {
"name": "Maura Healey",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; legislature overrides by two-thirds",
"Line-item, reduction and amendatory vetoes",
"Key appointments need consent of elected Governor's Council",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"MI": {
"name": "Jocelyn Benson",
"party": "D",
"termEnd": "2031-01-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto",
"Appoints judges, later subject to voter ratification",
"Appoints most department heads with Senate consent",
"Grants pardons (except impeachment); commands state militia",
"Limited to two four-year terms"
]
},
"MN": {
"name": "Amy Klobuchar",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto and pocket veto",
"Appoints department heads (commissioners)",
"Four-year terms, no term limit"
]
},
"MS": {
"name": "Tate Reeves",
"party": "R",
"termEnd": "2028-01",
"status": "continuing",
"note": "Term-limited.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto on appropriations only",
"Pardons and reprieves, except treason or impeachment",
"Little authority over the state budget process",
"Commander-in-chief of National Guard; calls special sessions",
"Two consecutive four-year terms"
]
},
"MO": {
"name": "Mike Kehoe",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto",
"Grants pardons, except impeachment cases",
"Commander-in-chief of the National Guard; convenes legislature",
"Limited to two terms"
]
},
"MT": {
"name": "Greg Gianforte",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "Term-limited.",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item and amendatory vetoes",
"Grants pardons and reprieves",
"Commander-in-chief; can convene legislature at any time",
"Eight years in any sixteen-year period"
]
},
"NE": {
"name": "Jim Pillen",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; unicameral Legislature overrides by three-fifths (30 votes)",
"Line-item and reduction veto",
"Calls special sessions limited to topics in proclamation",
"Two consecutive four-year terms"
]
},
"NV": {
"name": "Aaron Ford",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of elected members",
"No line-item veto",
"Pardons and reprieves, except treason or impeachment",
"Commander-in-chief; can convene legislature at any time",
"Limited to two four-year terms"
]
},
"NH": {
"name": "Kelly Ayotte",
"party": "R",
"termEnd": "2029-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of members present",
"No line-item veto",
"Pardons need approval of the elected Executive Council",
"Nominates judges, attorney general, Guard officers (Council approval)",
"Commander-in-chief of state military forces",
"Two-year terms, no term limit"
]
},
"NJ": {
"name": "Mikie Sherrill",
"party": "D",
"termEnd": "2030-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item and amendatory vetoes",
"Appoints entire cabinet, confirmed by the Senate",
"Appoints all Superior Court judges and county prosecutors",
"Commander-in-chief of the New Jersey National Guard",
"Two consecutive four-year terms"
]
},
"NM": {
"name": "Deb Haaland",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item veto",
"Submits the state budget",
"Commander-in-chief of the New Mexico National Guard",
"Two consecutive terms; may run again after one term out"
]
},
"NY": {
"name": "Kathy Hochul",
"party": "D",
"termEnd": "2031-01-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto and pocket veto",
"Grants pardons, except treason and impeachment",
"Appoints Executive Chamber without Senate confirmation",
"Commander-in-chief; can convene the Legislature",
"Four-year terms, no term limit"
]
},
"NC": {
"name": "Josh Stein",
"party": "D",
"termEnd": "2029-01-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"No line-item veto",
"Director of the state budget",
"Appoints some judges, executive officials and board members",
"Grants pardons; commands the North Carolina National Guard",
"Two consecutive four-year terms"
]
},
"ND": {
"name": "Kelly Armstrong",
"party": "R",
"termEnd": "2028-12-15",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislative Assembly overrides by two-thirds",
"Line-item veto",
"Can call the Legislative Assembly into emergency session",
"Commander-in-chief of state military forces",
"Limited to two four-year terms"
]
},
"OH": {
"name": "Amy Acton",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by three-fifths",
"Line-item veto",
"Drafts the budget proposal for the General Assembly",
"Grants pardons, except treason and impeachment",
"Appointments with Senate consent; fills statewide vacancies",
"Two consecutive four-year terms"
]
},
"OK": {
"name": "Mike Mazzei",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto on appropriations",
"Pardons only after a favorable Pardon and Parole Board vote",
"Prepares the state budget; appoints cabinet secretaries",
"Appoints appellate judges from nominating commission lists",
"Two consecutive four-year terms"
]
},
"OR": {
"name": "Tina Kotek",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds in both houses",
"Line-item veto on appropriation and emergency bills",
"Pardons and commutations; only reprieves for treason",
"Commander-in-chief of the Oregon Military Department",
"Calls special sessions; fills vacancies by appointment",
"Two terms in any 12-year period"
]
},
"PA": {
"name": "Josh Shapiro",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"Two consecutive four-year terms",
"No lifetime limit; may return after a break"
]
},
"RI": {
"name": "Helena Foulkes",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by three-fifths of members present",
"No line-item veto",
"Grants pardons",
"Submits the annual state budget",
"Commander-in-chief (Captain-General) of the National Guard",
"Two consecutive four-year terms"
]
},
"SC": {
"name": "Alan Wilson",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by two-thirds",
"Line-item veto",
"Submits an executive budget each January",
"Appoints 14 cabinet agency directors; shares other appointments",
"Clemency limited to commuting death sentences to life",
"Two consecutive four-year terms"
]
},
"SD": {
"name": "Larry Rhoden",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds",
"Line-item veto; amendatory veto on style or form only",
"Appoints cabinet and many boards and commissions",
"Grants pardons for state offenses",
"Commander-in-chief of the South Dakota National Guard",
"Two consecutive four-year terms"
]
},
"TN": {
"name": "Marsha Blackburn",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; General Assembly overrides by simple majority",
"Line-item veto on spending items",
"Appoints judges through the Tennessee Plan nominating commission",
"Appoints most state department heads",
"Commander-in-chief of National Guard and state militia",
"Two consecutive four-year terms"
]
},
"TX": {
"name": "Gina Hinojosa",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds of members present",
"Line-item veto",
"Pardons only on Board of Pardons and Paroles recommendation",
"Weak budget role; Legislative Budget Board leads",
"Commander-in-chief of Texas Military Forces; calls special sessions",
"Four-year terms, no term limit"
]
},
"UT": {
"name": "Spencer Cox",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of elected members",
"Line-item veto",
"Commander-in-chief of the Utah National Guard",
"Convenes the legislature on extraordinary occasions",
"No term limits (repealed in 2003)"
]
},
"VT": {
"name": "Phil Scott",
"party": "R",
"termEnd": "2029-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; override by two-thirds of members present",
"No line-item veto",
"Pardons and remits fines; only reprieves for treason",
"Commissions or appoints state officers",
"Captain-General and Commander-in-Chief of state forces",
"Two-year terms, no term limit"
]
},
"VA": {
"name": "Abigail Spanberger",
"party": "D",
"termEnd": "2030-01",
"status": "continuing",
"note": "Term-limited.",
"powers": [
"Veto; override by two-thirds of members present",
"Line-item and amendatory vetoes",
"Pardons and commutes sentences",
"Fills vacancies not appointed by the legislature",
"Commander-in-chief of the Virginia National Guard",
"Single four-year term; no immediate re-election"
]
},
"WA": {
"name": "Bob Ferguson",
"party": "D",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; override by two-thirds of members present",
"Section veto on any bill; line-item on spending",
"Commander-in-chief of state military forces",
"Four-year terms, no term limit"
]
},
"WV": {
"name": "Patrick Morrisey",
"party": "R",
"termEnd": "2029-01",
"status": "continuing",
"note": "",
"powers": [
"Veto; Legislature overrides by majority of elected members",
"Line-item and reduction veto",
"Pardons and reprieves, except House impeachment cases",
"Commander-in-chief; can convene the legislature at any time",
"Two consecutive four-year terms"
]
},
"WI": {
"name": "David Crowley",
"party": "D",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds of members present",
"Strong partial veto: strikes words in appropriation bills",
"Pardons, commutations, reprieves, except treason or impeachment",
"Appoints heads of agencies created by the legislature",
"Commander-in-chief of the Wisconsin National Guard",
"Four-year terms, no term limits"
]
},
"WY": {
"name": "Eric Barlow",
"party": "R",
"termEnd": "2031-01",
"status": "elected-2026",
"note": "End of term deduced from the term length.",
"powers": [
"Veto; Legislature overrides by two-thirds of elected members",
"Line-item veto",
"Commander-in-chief of the Wyoming National Guard",
"Eight years in any sixteen-year period"
]
}
}
}
+3592
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
{
"lastRun": {
"startedAt": "2026-11-13T14:34:53+00:00",
"finishedAt": "2026-11-13T14:35:08+00:00",
"mode": "election",
"requestedMode": "auto",
"electionYear": 2026,
"updated": [
"governors",
"house",
"legislatures",
"senate"
],
"warnings": [
"State legislatures: previous figures kept for 1 chamber(s) whose Wikipedia data did not add up: Louisiana State Senate (infobox seats add up to 37 instead of 39).",
"State legislatures: Wikipedia has no 2026 results yet for 16 chamber(s); the earlier figures were kept: Alaska State Senate, Alaska House of Representatives, California State Senate, California State Assembly, Colorado House of Representatives, Indiana State Senate, Maine House of Representatives, Maryland House of Delegates, Massachusetts House of Representatives, Nebraska Legislature, New Hampshire House of Representatives, North Dakota House of Representatives, Ohio House of Representatives, Texas House of Representatives, Utah State Senate, Utah House of Representatives."
],
"requests": 9
},
"seedFooter": "Data: English Wikipedia (2026 U.S. Senate, House, gubernatorial and state legislative election articles, the current-officeholder lists and each state's “Governor of …” and legislature articles), read on November 13, 2026, ten days after the election. Results that were not final on that date are marked “Not yet called”. State legislature leaders for 2027 are often chosen in December or January; where none was named yet, the current leader is shown and noted."
}
+913
View File
@@ -0,0 +1,913 @@
{
"meta": {
"mode": "election",
"electionYear": 2026,
"asOf": "2026-11-13T14:35:02+00:00",
"sources": [
"2026 United States Senate elections",
"List of current United States senators"
]
},
"data": {
"AL": [
{
"name": "Barry Moore",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Katie Britt",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"AK": [
{
"name": null,
"party": null,
"termEnd": "2033-01-03",
"class": 2,
"status": "uncalled",
"note": "Not yet called; Mary Peltola (D) vs Dan S. Sullivan (R)."
},
{
"name": "Lisa Murkowski",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"AZ": [
{
"name": "Ruben Gallego",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Mark Kelly",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"AR": [
{
"name": "Tom Cotton",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "John Boozman",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"CA": [
{
"name": "Adam Schiff",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Alex Padilla",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"CO": [
{
"name": "John Hickenlooper",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Michael Bennet",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"CT": [
{
"name": "Chris Murphy",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Richard Blumenthal",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"DE": [
{
"name": "Lisa Blunt Rochester",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Chris Coons",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"FL": [
{
"name": "Rick Scott",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ashley Moody",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "elected-2026",
"note": "Won 2026 special election for the remainder of the Class 3 term."
}
],
"GA": [
{
"name": "Jon Ossoff",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Raphael Warnock",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"HI": [
{
"name": "Mazie Hirono",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Brian Schatz",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"ID": [
{
"name": "Jim Risch",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Mike Crapo",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"IL": [
{
"name": "Juliana Stratton",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Tammy Duckworth",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"IN": [
{
"name": "Jim Banks",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Todd Young",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"IA": [
{
"name": "Josh Turek",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Chuck Grassley",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"KS": [
{
"name": "Adam Hamilton",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Jerry Moran",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"KY": [
{
"name": "Andy Barr",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Rand Paul",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"LA": [
{
"name": "Julia Letlow",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "John Kennedy",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"ME": [
{
"name": "Angus King",
"party": "I",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Independent, caucuses with Democrats."
},
{
"name": "Troy Jackson",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MD": [
{
"name": "Angela Alsobrooks",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Chris Van Hollen",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"MA": [
{
"name": "Elizabeth Warren",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ed Markey",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MI": [
{
"name": "Elissa Slotkin",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Abdul El-Sayed",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MN": [
{
"name": "Amy Klobuchar",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Elected Governor of Minnesota in 2026; the Senate seat will be filled after the new governor takes office."
},
{
"name": "Peggy Flanagan",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MS": [
{
"name": "Roger Wicker",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Scott Colom",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"MO": [
{
"name": "Josh Hawley",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Eric Schmitt",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"MT": [
{
"name": "Tim Sheehy",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Kurt Alme",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NE": [
{
"name": "Deb Fischer",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Pete Ricketts",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NV": [
{
"name": "Jacky Rosen",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Catherine Cortez Masto",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"NH": [
{
"name": "Chris Pappas",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Maggie Hassan",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"NJ": [
{
"name": "Andy Kim",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Cory Booker",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NM": [
{
"name": "Martin Heinrich",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ben Ray Luján",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"NY": [
{
"name": "Kirsten Gillibrand",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Chuck Schumer",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"NC": [
{
"name": "Roy Cooper",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Ted Budd",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"ND": [
{
"name": "Kevin Cramer",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "John Hoeven",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"OH": [
{
"name": "Bernie Moreno",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Sherrod Brown",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "elected-2026",
"note": "Won 2026 special election for the remainder of the Class 3 term."
}
],
"OK": [
{
"name": "Kevin Hern",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "James Lankford",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"OR": [
{
"name": "Jeff Merkley",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Ron Wyden",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"PA": [
{
"name": "Dave McCormick",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "John Fetterman",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"RI": [
{
"name": "Sheldon Whitehouse",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Jack Reed",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"SC": [
{
"name": "Annie Andrews",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "Tim Scott",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"SD": [
{
"name": "Mike Rounds",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
},
{
"name": "John Thune",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"TN": [
{
"name": "Marsha Blackburn",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Elected Governor of Tennessee in 2026; the Senate seat will be filled after the new governor takes office."
},
{
"name": "Bill Hagerty",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"TX": [
{
"name": "Ted Cruz",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "James Talarico",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"UT": [
{
"name": "John Curtis",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Mike Lee",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"VT": [
{
"name": "Bernie Sanders",
"party": "I",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": "Independent, caucuses with Democrats."
},
{
"name": "Peter Welch",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"VA": [
{
"name": "Tim Kaine",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Mark Warner",
"party": "D",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"WA": [
{
"name": "Maria Cantwell",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Patty Murray",
"party": "D",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"WV": [
{
"name": "Jim Justice",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Shelley Moore Capito",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
],
"WI": [
{
"name": "Tammy Baldwin",
"party": "D",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Ron Johnson",
"party": "R",
"termEnd": "2029-01-03",
"class": 3,
"status": "continuing",
"note": ""
}
],
"WY": [
{
"name": "John Barrasso",
"party": "R",
"termEnd": "2031-01-03",
"class": 1,
"status": "continuing",
"note": ""
},
{
"name": "Harriet Hageman",
"party": "R",
"termEnd": "2033-01-03",
"class": 2,
"status": "elected-2026",
"note": ""
}
]
}
}
+11
View File
@@ -0,0 +1,11 @@
services:
app:
build: .
image: us-officeholders-map:latest
ports:
- "127.0.0.1:8080:8080"
volumes:
- ./data:/data
environment:
UPDATE_MODE: ${UPDATE_MODE:-auto}
restart: unless-stopped