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

+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