Generate an evidence-backed NextPath career catalog

This commit is contained in:
juvenal.diaz 2026-12-05 19:30:47 -06:00
parent 73e4fd5ec4
commit 8f305e8b75
2 changed files with 244 additions and 0 deletions

View File

@ -0,0 +1,213 @@
#!/usr/bin/env python3
"""Build a broad Arizona NextPath catalog from official public datasets."""
from __future__ import annotations
import argparse
import csv
import io
import json
import os
import tempfile
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
from collections import defaultdict
from pathlib import Path
from typing import Any
ONET_URL = "https://www.onetcenter.org/dl_files/database/db_31_0_csv.zip"
CROSSWALK_URL = "https://nces.ed.gov/ipeds/cipcode/Files/CIP2020_SOC2018_Crosswalk.xlsx"
IPEDS_URL = "https://nces.ed.gov/ipeds/datacenter/data"
PROJECTIONS_URL = "https://public.projectionscentral.org/Projections/LongTermRestJson/04"
RIASEC = ("Realistic", "Investigative", "Artistic", "Social", "Enterprising", "Conventional")
RIASEC_CODES = {name: name[0] for name in RIASEC}
def 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=180) as response, temporary.open("wb") as stream:
while block := response.read(1024 * 1024):
stream.write(block)
os.replace(temporary, path)
return path
def csv_member(path: Path, suffix: str) -> list[dict[str, str]]:
with zipfile.ZipFile(path) as archive:
name = next(name for name in archive.namelist() if name.lower().endswith(suffix.lower()))
with archive.open(name) as raw:
return list(csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8-sig", errors="replace")))
def xlsx_rows(path: Path, sheet_number: int) -> list[list[str]]:
namespace = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
with zipfile.ZipFile(path) as archive:
shared = []
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
for item in root.findall(namespace + "si"):
shared.append("".join(node.text or "" for node in item.iter(namespace + "t")))
sheet = ET.fromstring(archive.read(f"xl/worksheets/sheet{sheet_number}.xml"))
rows = []
for row in sheet.iter(namespace + "row"):
values = []
for cell in row.findall(namespace + "c"):
value = cell.find(namespace + "v")
text = "" if value is None else value.text or ""
if cell.get("t") == "s" and text:
text = shared[int(text)]
values.append(text)
rows.append(values)
return rows
def projections() -> dict[str, dict[str, Any]]:
results: dict[str, dict[str, Any]] = {}
page = 0
while True:
with urllib.request.urlopen(f"{PROJECTIONS_URL}?page={page}", timeout=60) as response:
body = json.load(response)
for row in body.get("rows", []):
code = row.get("OccCode", "")
if len(code) == 7 and code[2] == "-":
results[code] = row
pager = body.get("pager", {})
if page + 1 >= int(pager.get("total_pages", 1)):
return results
page += 1
def atomic_json(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}-", dir=path.parent)
try:
with os.fdopen(descriptor, "w") as stream:
json.dump(payload, stream, indent=2, sort_keys=True)
stream.write("\n")
os.chmod(temporary, 0o600)
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def refresh(seed_catalog_path: Path, seed_mapping_path: Path, catalog_path: Path, mapping_path: Path, cache: Path, limit: int) -> None:
seed_catalog = json.loads(seed_catalog_path.read_text())
seed_mapping = json.loads(seed_mapping_path.read_text())
seed_occupations = {item["onet_soc"]: item for item in seed_catalog["occupations"]}
required_soc = {code.split(".", 1)[0] for code in seed_occupations}
onet_path = download(ONET_URL, cache / "onet" / "db_31_0_csv.zip")
crosswalk_path = download(CROSSWALK_URL, cache / "nces" / "CIP2020_SOC2018_Crosswalk.xlsx")
directory_path = download(f"{IPEDS_URL}/HD2024.zip", cache / "ipeds" / "HD2024.zip")
completions_path = download(f"{IPEDS_URL}/C2024_A.zip", cache / "ipeds" / "C2024_A.zip")
occupations = csv_member(onet_path, "occupation_data.csv")
interests = csv_member(onet_path, "career_interest_types.csv")
by_soc: dict[str, list[dict[str, str]]] = defaultdict(list)
for occupation in occupations:
by_soc[occupation["O*NET-SOC Code"].split(".", 1)[0]].append(occupation)
chosen: dict[str, dict[str, str]] = {}
for soc, variants in by_soc.items():
chosen[soc] = next((item for item in variants if item["O*NET-SOC Code"].endswith(".00")), variants[0])
profiles: dict[str, dict[str, float]] = defaultdict(dict)
for row in interests:
if row.get("Scale ID") == "OI" and row.get("Element Name") in RIASEC:
profiles[row["O*NET-SOC Code"]][row["Element Name"]] = float(row["Data Value"])
soc_cips: dict[str, set[str]] = defaultdict(set)
rows = xlsx_rows(crosswalk_path, 3) # Official SOC-CIP worksheet.
for row in rows[1:]:
if len(row) >= 3 and len(row[0]) == 7:
soc_cips[row[0]].add(row[2].replace(".", ""))
arizona_units = {row["UNITID"] for row in csv_member(directory_path, "HD2024.csv") if row.get("STABBR") == "AZ"}
cip_completions: dict[str, int] = defaultdict(int)
for row in csv_member(completions_path, "C2024_A.csv"):
if row.get("UNITID") not in arizona_units or row.get("MAJORNUM") != "1":
continue
count = int(row.get("CTOTALT") or -1)
if count > 0:
cip_completions[row.get("CIPCODE", "").replace(".", "")] += count
projected = projections()
candidates = []
for soc, occupation in chosen.items():
profile = profiles.get(occupation["O*NET-SOC Code"], {})
cips = sorted(cip for cip in soc_cips.get(soc, set()) if cip_completions.get(cip, 0) > 0)
projection = projected.get(soc)
if len(profile) != len(RIASEC) or not cips or not projection:
continue
openings = int(str(projection.get("AvgAnnualOpenings", "0")).replace(",", ""))
if openings <= 0:
continue
candidates.append((soc, occupation, profile, cips, openings, sum(cip_completions[cip] for cip in cips)))
candidates.sort(key=lambda item: (item[4], item[5], item[1]["Title"]), reverse=True)
selected = []
selected_soc = set()
for candidate in candidates:
if candidate[0] in required_soc:
selected.append(candidate)
selected_soc.add(candidate[0])
for candidate in candidates:
if len(selected) >= limit:
break
if candidate[0] not in selected_soc:
selected.append(candidate)
selected_soc.add(candidate[0])
missing = required_soc - selected_soc
if missing:
raise ValueError(f"required seed occupations lost during expansion: {sorted(missing)}")
catalog_items = []
mappings = {}
for soc, occupation, profile, cips, _openings, _graduates in selected:
code = occupation["O*NET-SOC Code"]
seed = next((item for item in seed_occupations.values() if item["onet_soc"].split(".", 1)[0] == soc), None)
order = [RIASEC_CODES[name] for name in sorted(RIASEC, key=lambda name: (-profile[name], name))[:3]]
catalog_items.append(seed or {
"onet_soc": code,
"title": occupation["Title"],
"interest_order": order,
"summary": occupation["Description"],
"try_first": "Review the daily work, compare Arizona programs, and arrange an informational interview or supervised job shadow.",
"source_url": f"https://www.onetonline.org/link/summary/{code}",
})
seed_spec = next((spec for key, spec in seed_mapping["mappings"].items() if key.split(".", 1)[0] == soc), None)
mappings[code] = {
"cip6": seed_spec["cip6"] if seed_spec else cips,
"coverage": seed_spec["coverage"] if seed_spec else 0.7,
"job_query": seed_spec["job_query"] if seed_spec else occupation["Title"],
}
catalog_items.sort(key=lambda item: item["title"])
version = "nextpath-auto-onet31-cip2020-ipeds2024"
atomic_json(catalog_path, {"version": version, "occupations": catalog_items})
atomic_json(mapping_path, {
"version": version,
"source_url": CROSSWALK_URL,
"mappings": mappings,
})
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--seed-catalog", type=Path, required=True)
parser.add_argument("--seed-mapping", type=Path, required=True)
parser.add_argument("--catalog-output", type=Path, required=True)
parser.add_argument("--mapping-output", type=Path, required=True)
parser.add_argument("--cache", type=Path, required=True)
parser.add_argument("--limit", type=int, default=75)
arguments = parser.parse_args()
if arguments.limit < 12 or arguments.limit > 200:
parser.error("--limit must be between 12 and 200")
refresh(arguments.seed_catalog, arguments.seed_mapping, arguments.catalog_output, arguments.mapping_output, arguments.cache, arguments.limit)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,31 @@
import importlib.util
import json
import pathlib
import tempfile
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
SPEC = importlib.util.spec_from_file_location(
"nextpath_catalog_refresh", ROOT / "scripts" / "nextpath-catalog-refresh.py"
)
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)
class NextPathCatalogRefreshTests(unittest.TestCase):
def test_atomic_json_replaces_catalog_with_private_permissions(self):
with tempfile.TemporaryDirectory() as temporary:
path = pathlib.Path(temporary) / "catalog.json"
path.write_text("old")
MODULE.atomic_json(path, {"version": "generated", "occupations": []})
self.assertEqual(json.loads(path.read_text())["version"], "generated")
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
def test_riasec_codes_cover_every_official_interest_name(self):
self.assertEqual(set(MODULE.RIASEC_CODES), set(MODULE.RIASEC))
self.assertEqual(set(MODULE.RIASEC_CODES.values()), set("RIASEC"))
if __name__ == "__main__":
unittest.main()