Add NextPath labor evidence refresh

This commit is contained in:
juvenal.diaz 2026-12-05 14:00:57 -06:00
parent 8471f4c34d
commit 64dd4e1eee
3 changed files with 207 additions and 0 deletions

View File

@ -0,0 +1,18 @@
{
"version": "nextpath-soc-cip-2026-01",
"source_url": "https://nces.ed.gov/ipeds/cipcode/resources.aspx?y=56",
"mappings": {
"15-1252.00": {"cip4": ["1107"], "coverage": 0.8},
"29-1141.00": {"cip4": ["5138"], "coverage": 0.9},
"47-2111.00": {"cip4": ["4603"], "coverage": 0.8},
"49-9021.00": {"cip4": ["4702"], "coverage": 0.8},
"25-2021.00": {"cip4": ["1312"], "coverage": 0.7},
"27-1024.00": {"cip4": ["5004"], "coverage": 0.7},
"13-2011.00": {"cip4": ["5203"], "coverage": 0.9},
"17-2051.00": {"cip4": ["1408"], "coverage": 0.9},
"35-1011.00": {"cip4": ["1205"], "coverage": 0.7},
"21-1012.00": {"cip4": ["1311", "4407"], "coverage": 0.6},
"13-1081.00": {"cip4": ["5202"], "coverage": 0.7},
"29-1292.00": {"cip4": ["5106"], "coverage": 0.9}
}
}

View File

@ -0,0 +1,155 @@
#!/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 json
import os
import tempfile
import urllib.parse
import urllib.request
from collections.abc import Iterable
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
SCORECARD_URL = "https://api.data.gov/ed/collegescorecard/v1/schools.json"
CAREERONESTOP = "https://api.careeronestop.org"
def get_json(url: str, token: str = "", timeout: int = 45) -> dict[str, Any]:
headers = {"Accept": "application/json", "User-Agent": "NextPath/1.0"}
if token:
headers["Authorization"] = f"Bearer {token}"
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=timeout) as response:
return json.load(response)
def scorecard_programs(api_key: str) -> list[dict[str, Any]]:
fields = "id,ope6_id,school.name,latest.programs.cip_4_digit"
programs: list[dict[str, Any]] = []
page = 0
while True:
query = urllib.parse.urlencode({
"api_key": api_key,
"school.state": "AZ",
"per_page": 100,
"page": page,
"fields": fields,
})
body = get_json(f"{SCORECARD_URL}?{query}")
for school in body.get("results", []):
programs.extend(school.get("latest.programs.cip_4_digit") or [])
metadata = body.get("metadata", {})
if (page + 1) * int(metadata.get("per_page", 100)) >= int(metadata.get("total", 0)):
return programs
page += 1
def annual_completions(programs: Iterable[dict[str, Any]], cip4: set[str]) -> int:
# Scorecard calls this IPEDS awards. Deduplicate branch records sharing the
# same OPE6 institution and program, retaining the largest reported value.
deduplicated: dict[tuple[str, str], int] = {}
for program in programs:
code = str(program.get("code", "")).replace(".", "").zfill(4)
if code not in cip4:
continue
awards = program.get("counts", {}).get("ipeds_awards1")
if not isinstance(awards, (int, float)) or awards < 0:
continue
key = (str(program.get("ope6_id") or program.get("unit_id")), code)
deduplicated[key] = max(deduplicated.get(key, 0), int(awards))
return sum(deduplicated.values())
def projected_openings(body: dict[str, Any]) -> tuple[int, str]:
details = body.get("OccupationDetail") or []
if not details:
raise ValueError("CareerOneStop returned no occupation details")
projections = details[0].get("Projections") or {}
rows = projections.get("Projections") or []
row = next((item for item in rows if item.get("StateName") == "Arizona"), rows[0] if rows else None)
if not row:
raise ValueError("CareerOneStop returned no Arizona projection")
count = int(str(row.get("ProjectedAnnualJobOpening", "0")).replace(",", ""))
period = f"{row.get('EstimatedYear', projections.get('EstimatedYear', ''))}-{row.get('ProjectedYear', projections.get('ProjectedYear', ''))}"
return count, period.strip("-")
def career_one_stop(user_id: str, token: str, onet: str) -> tuple[int, str, int]:
path = "/".join(urllib.parse.quote(part, safe="") for part in (user_id, onet, "AZ"))
details = get_json(
f"{CAREERONESTOP}/v1/occupation/{path}?projectedEmployment=true&enableMetaData=true",
token,
)
openings, period = projected_openings(details)
job_path = "/".join(urllib.parse.quote(str(part), safe="") for part in (
user_id, onet, "AZ", 0, 0, 0, 0, 1, 30,
))
jobs = get_json(f"{CAREERONESTOP}/v2/jobsearch/{job_path}?enableMetaData=true", token)
return openings, period, int(jobs.get("TotalJobCount", 0))
def refresh(mapping_path: Path, output_path: Path, user_id: str, token: str, api_key: str) -> None:
mapping = json.loads(mapping_path.read_text())
programs = scorecard_programs(api_key)
observed = datetime.now(timezone.utc)
occupations: dict[str, Any] = {}
for onet, spec in mapping["mappings"].items():
graduates = annual_completions(programs, set(spec["cip4"]))
openings, period, postings = career_one_stop(user_id, token, onet)
if graduates <= 0:
raise ValueError(f"no Arizona completions found for {onet}")
occupations[onet] = {
"arizona_annual_graduates": graduates,
"arizona_projected_annual_openings": openings,
"active_entry_level_postings": postings,
"graduate_academic_year": "latest College Scorecard IPEDS awards cohort",
"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://collegescorecard.ed.gov/data/",
"projection_source_url": "https://api.careeronestop.org/api-explorer/home/index/Occupations_GetOccupationDetails",
"posting_source_url": "https://api.careeronestop.org/api-explorer/home/index/JobSearchV2_GetJobsByKeywordAndOnetCode",
}
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)
parser.add_argument("--user-id", default=os.environ.get("CAREERONESTOP_USER_ID", ""))
parser.add_argument("--token", default=os.environ.get("CAREERONESTOP_API_TOKEN", ""))
parser.add_argument("--data-gov-key", default=os.environ.get("DATA_GOV_API_KEY", "DEMO_KEY"))
args = parser.parse_args()
if not args.user_id or not args.token:
parser.error("CareerOneStop user ID and API token are required")
refresh(args.mapping, args.output, args.user_id, args.token, args.data_gov_key)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,34 @@
import importlib.util
import pathlib
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
SPEC = importlib.util.spec_from_file_location(
"nextpath_refresh", ROOT / "scripts" / "nextpath-opportunity-refresh.py"
)
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)
class NextPathOpportunityRefreshTests(unittest.TestCase):
def test_completions_deduplicate_branches(self):
programs = [
{"code": "11.07", "ope6_id": "one", "counts": {"ipeds_awards1": 10}},
{"code": "1107", "ope6_id": "one", "counts": {"ipeds_awards1": 8}},
{"code": "1107", "ope6_id": "two", "counts": {"ipeds_awards1": 5}},
{"code": "5138", "ope6_id": "three", "counts": {"ipeds_awards1": 99}},
]
self.assertEqual(MODULE.annual_completions(programs, {"1107"}), 15)
def test_extracts_arizona_projection(self):
body = {"OccupationDetail": [{"Projections": {
"EstimatedYear": "2022", "ProjectedYear": "2032", "Projections": [
{"StateName": "Arizona", "ProjectedAnnualJobOpening": "1,234", "EstimatedYear": "2022", "ProjectedYear": "2032"}
]
}}]}
self.assertEqual(MODULE.projected_openings(body), (1234, "2022-2032"))
if __name__ == "__main__":
unittest.main()