my-homelab-configs/scripts/nextpath-opportunity-refres...

157 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""Refresh NextPath's source-attributed Arizona opportunity cache.
The output is replaced atomically only after every occupation has complete
evidence. A failed or rate-limited source therefore cannot erase a previously
successful snapshot.
"""
from __future__ import annotations
import argparse
import csv
import io
import json
import os
import tempfile
import urllib.parse
import urllib.request
import zipfile
from collections.abc import Iterable
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
IPEDS_URL = "https://nces.ed.gov/ipeds/datacenter/data"
IPEDS_YEARS = (2022, 2023, 2024)
PROJECTIONS_CENTRAL = "https://public.projectionscentral.org/Projections/LongTermRestJson"
AYLA_JOBS = "https://aylagov.com/api/jobs/search"
def get_json(url: str, timeout: int = 45) -> dict[str, Any]:
headers = {"Accept": "application/json", "User-Agent": "NextPath/1.0"}
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=timeout) as response:
return json.load(response)
def cached_download(url: str, path: Path) -> Path:
if path.is_file() and path.stat().st_size > 0:
return path
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
request = urllib.request.Request(url, headers={"User-Agent": "NextPath/1.0"})
with urllib.request.urlopen(request, timeout=120) as response, temporary.open("wb") as stream:
while block := response.read(1024 * 1024):
stream.write(block)
os.replace(temporary, path)
return path
def zip_rows(path: Path) -> Iterable[dict[str, str]]:
with zipfile.ZipFile(path) as archive:
name = archive.namelist()[0]
with archive.open(name) as raw:
# IPEDS changed encodings across annual exports: newer headers can
# carry a UTF-8 BOM while older institution names contain legacy
# bytes. Replacement is safe because matching uses ASCII IDs,
# state abbreviations and CIP fields rather than institution text.
yield from csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8-sig", errors="replace"))
def ipeds_completion_history(cip6: set[str], cache_dir: Path) -> dict[str, int]:
history: dict[str, int] = {}
for year in IPEDS_YEARS:
directory = cached_download(f"{IPEDS_URL}/HD{year}.zip", cache_dir / f"HD{year}.zip")
completions = cached_download(f"{IPEDS_URL}/C{year}_A.zip", cache_dir / f"C{year}_A.zip")
arizona = {row["UNITID"] for row in zip_rows(directory) if row.get("STABBR") == "AZ"}
total = 0
for row in zip_rows(completions):
code = row.get("CIPCODE", "").replace(".", "")
if row.get("UNITID") not in arizona or code not in cip6 or row.get("MAJORNUM") != "1":
continue
awards = int(row.get("CTOTALT") or -1)
if awards >= 0:
total += awards
history[str(year)] = total
return history
def projected_openings(body: dict[str, Any]) -> tuple[int, str, float]:
rows = body.get("rows") or []
row = next((item for item in rows if item.get("Area") == "Arizona"), rows[0] if rows else None)
if not row:
raise ValueError("Projections Central returned no Arizona projection")
count = int(str(row.get("AvgAnnualOpenings", "0")).replace(",", ""))
period = f"{row.get('BaseYear', '')}-{row.get('ProjYear', '')}"
return count, period.strip("-"), float(row.get("PercentChange", 0))
def public_market_evidence(onet: str, job_query: str) -> tuple[int, str, float, int]:
soc = onet.split(".", 1)[0]
projections = get_json(f"{PROJECTIONS_CENTRAL}/04/{urllib.parse.quote(soc, safe='-')}")
openings, period, growth = projected_openings(projections)
query = urllib.parse.urlencode({
"search": job_query,
"limit": 1,
"filters": json.dumps({"state": "AZ"}, separators=(",", ":")),
})
jobs = get_json(f"{AYLA_JOBS}?{query}")
return openings, period, growth, int(jobs.get("pagination", {}).get("total", 0))
def refresh(mapping_path: Path, output_path: Path) -> None:
mapping = json.loads(mapping_path.read_text())
source_cache = output_path.parent / "source-cache" / "ipeds"
observed = datetime.now(timezone.utc)
occupations: dict[str, Any] = {}
for onet, spec in mapping["mappings"].items():
history = ipeds_completion_history(set(spec["cip6"]), source_cache)
graduates = history[str(IPEDS_YEARS[-1])]
openings, period, growth, postings = public_market_evidence(onet, spec["job_query"])
if graduates <= 0:
raise ValueError(f"no Arizona completions found for {onet}")
occupations[onet] = {
"arizona_annual_graduates": graduates,
"arizona_graduate_history": history,
"arizona_projected_annual_openings": openings,
"projected_employment_growth_percent": growth,
"active_postings": postings,
"graduate_academic_year": str(IPEDS_YEARS[-1]),
"projection_period": period,
"postings_observed_at": observed.isoformat().replace("+00:00", "Z"),
"geography": "Arizona",
"soc_to_cip_mapping_coverage": spec["coverage"],
"graduate_source_url": "https://nces.ed.gov/ipeds/use-the-data/download-access-database",
"projection_source_url": "https://projectionscentral.org/directdownloads",
"posting_source_url": "https://aylagov.com/developers",
}
payload = {
"version": "nextpath-opportunity-cache-v1",
"generated_at": observed.isoformat().replace("+00:00", "Z"),
"mapping_version": mapping["version"],
"occupations": occupations,
}
output_path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=".opportunity-", suffix=".json", dir=output_path.parent)
try:
with os.fdopen(fd, "w") as stream:
json.dump(payload, stream, indent=2, sort_keys=True)
stream.write("\n")
os.chmod(temporary, 0o600)
os.replace(temporary, output_path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--mapping", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
refresh(args.mapping, args.output)
if __name__ == "__main__":
main()