156 lines
6.7 KiB
Python
156 lines
6.7 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 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()
|