#!/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" CENSUS_ZCTA = "https://www2.census.gov/geo/docs/maps-data/data/gazetteer/2024_Gazetteer/2024_Gaz_zcta_national.zip" AWARD_LEVELS = { "1": "certificate under one year", "20": "certificate under 12 weeks", "21": "certificate 12 weeks to under one year", "2": "certificate one to two years", "3": "associate degree", "4": "certificate two to four years", "5": "bachelor degree", "6": "post-baccalaureate certificate", "7": "master degree", "8": "post-master certificate", "17": "research doctorate", "18": "professional doctorate", "19": "other doctorate", } 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 integer(value: Any, default: int = -1) -> int: try: return int(value) except (TypeError, ValueError): return default def decimal(value: Any, default: float = 0) -> float: try: return float(value) except (TypeError, ValueError): return default def keyed_rows(path: Path) -> dict[str, dict[str, str]]: return {row["UNITID"]: row for row in zip_rows(path) if row.get("UNITID")} def arizona_education_options(mapping: dict[str, Any], cache_dir: Path) -> tuple[dict[str, Any], dict[str, Any]]: directory_path = cached_download(f"{IPEDS_URL}/HD2024.zip", cache_dir / "HD2024.zip") completion_path = cached_download(f"{IPEDS_URL}/C2024_A.zip", cache_dir / "C2024_A.zip") tuition_path = cached_download(f"{IPEDS_URL}/IC2023_AY.zip", cache_dir / "IC2023_AY.zip") admissions_path = cached_download(f"{IPEDS_URL}/ADM2023.zip", cache_dir / "ADM2023.zip") characteristics_path = cached_download(f"{IPEDS_URL}/IC2023.zip", cache_dir / "IC2023.zip") graduation_path = cached_download(f"{IPEDS_URL}/DRVGR2023.zip", cache_dir / "DRVGR2023.zip") zcta_path = cached_download(CENSUS_ZCTA, cache_dir.parent / "census" / "2024_Gaz_zcta_national.zip") directory = {row["UNITID"]: row for row in zip_rows(directory_path) if row.get("STABBR") == "AZ"} tuition = keyed_rows(tuition_path) admissions = keyed_rows(admissions_path) characteristics = keyed_rows(characteristics_path) graduation = keyed_rows(graduation_path) cip_to_onet: dict[str, list[str]] = {} for onet, spec in mapping["mappings"].items(): for cip in spec["cip6"]: cip_to_onet.setdefault(cip, []).append(onet) awards: dict[tuple[str, str], int] = {} award_levels: dict[tuple[str, str], set[str]] = {} for row in zip_rows(completion_path): unit = row.get("UNITID", "") cip = row.get("CIPCODE", "").replace(".", "") count = integer(row.get("CTOTALT")) if unit not in directory or cip not in cip_to_onet or row.get("MAJORNUM") != "1" or count <= 0: continue key = (unit, cip) awards[key] = awards.get(key, 0) + count award_levels.setdefault(key, set()).add(row.get("AWLEVEL", "")) options: dict[str, list[dict[str, Any]]] = {onet: [] for onet in mapping["mappings"]} for (unit, cip), completions in awards.items(): institution = directory[unit] annual_tuition = integer(tuition.get(unit, {}).get("TUITION2")) if annual_tuition < 0: annual_tuition = 0 open_admission = characteristics.get(unit, {}).get("OPENADMP") == "1" applications = integer(admissions.get(unit, {}).get("APPLCN"), 0) admitted = integer(admissions.get(unit, {}).get("ADMSSN"), 0) admission_rate = 100.0 if open_admission else (100 * admitted / applications if applications > 0 else 0) admission_basis = "open admissions" if open_admission else ("reported admission rate" if applications > 0 else "admission rate not reported") completion_rate = integer(graduation.get(unit, {}).get("GRRTTOT"), 0) if completion_rate < 0: completion_rate = 0 website = institution.get("WEBADDR", "").strip() if website and not website.startswith(("http://", "https://")): website = "https://" + website record = { "unit_id": unit, "institution": institution.get("INSTNM", ""), "city": institution.get("CITY", ""), "zip_code": institution.get("ZIP", "").split("-", 1)[0], "latitude": decimal(institution.get("LATITUDE")), "longitude": decimal(institution.get("LONGITUD")), "website": website, "cip6": cip, "award_levels": [AWARD_LEVELS.get(level, f"IPEDS award level {level}") for level in sorted(award_levels[(unit, cip)]) if level], "program_completions": completions, "annual_in_state_tuition": annual_tuition, "admission_rate_percent": round(admission_rate, 1), "admission_basis": admission_basis, "institution_completion_rate_percent": completion_rate, "program_year": "2024", "cost_admission_year": "2023", } for onet in cip_to_onet[cip]: options[onet].append(record) zip_coordinates: dict[str, dict[str, float]] = {} with zipfile.ZipFile(zcta_path) as archive: with archive.open(archive.namelist()[0]) as raw: reader = csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8-sig"), delimiter="\t") for original in reader: row = {key.strip(): value.strip() for key, value in original.items()} code = row.get("GEOID", "") if code.startswith(("85", "86")): zip_coordinates[code] = {"latitude": decimal(row.get("INTPTLAT")), "longitude": decimal(row.get("INTPTLONG"))} return options, zip_coordinates 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] = {} education, zip_coordinates = arizona_education_options(mapping, source_cache) 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-v2", "generated_at": observed.isoformat().replace("+00:00", "Z"), "mapping_version": mapping["version"], "occupations": occupations, "education_options": education, "zip_coordinates": zip_coordinates, "education_sources": { "institutions_programs_cost_access_quality": "https://nces.ed.gov/ipeds/use-the-data", "zip_coordinates": "https://www.census.gov/geographies/reference-files/time-series/geo/gazetteer-files.2024.html", }, } 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()