Files

128 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Regenerate scripts/taxonomy.py from https://www.levels.fyi/t.
python3 scripts/fetch_taxonomy.py
/t embeds the whole catalog in __NEXT_DATA__: every job family with its
category, its focus tags (with their sub-tags) and its job titles (with their
aliases). One public page, no sign-in. The output is a checked-in module, so a
change in Levels.fyi's catalog shows up as a diff a human reviews.
"""
from __future__ import annotations
import gzip
import json
import re
import sys
import urllib.error
import urllib.request
import lib
URL = "https://www.levels.fyi/t"
OUT = lib.ROOT / "scripts" / "taxonomy.py"
UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/128.0 Safari/537.36")
HEADER = '''"""Levels.fyi's role catalog. Generated by fetch_taxonomy.py on {date}.
ROLES maps a job-family slug to (name, category). SPECIALIZATIONS maps a role
to its focus tags, each a slug to (name, other labels authors write instead,
including sub-tags). TITLES maps a role to its job titles, each a slug to
(name, aliases). Titles also live nested under their focus tag, which is what
TITLE_TO_SPEC records: a row with no focusTag but a known title still gets
its specialization. Slugs are what the API's jobFamilySlug/focusTag/title
fields reduce to; the labels are what submissions actually carry.
Regenerate with `python3 scripts/fetch_taxonomy.py`; do not edit by hand.
"""
'''
def catalog() -> dict:
request = urllib.request.Request(
URL, headers={"User-Agent": UA, "Accept-Encoding": "gzip",
"Accept": "text/html,application/xhtml+xml"})
with urllib.request.urlopen(request, timeout=30) as response:
raw = response.read()
if response.headers.get("Content-Encoding") == "gzip":
raw = gzip.decompress(raw)
found = re.search(r'<script id="__NEXT_DATA__"[^>]*>(.*?)</script>',
raw.decode("utf-8", "replace"), re.S)
if not found:
raise SystemExit(f"{URL} carried no __NEXT_DATA__; the page shape changed")
return json.loads(found.group(1))["props"]["pageProps"]["jobFamilies"]
def aliases(*names) -> list[str]:
out: list[str] = []
for name in names:
if name and name not in out:
out.append(name)
return out
def emit(families: dict) -> str:
roles, specs, titles, title_spec = {}, {}, {}, {}
for category, members in families.items():
for family in members:
slug = family["slug"]
roles[slug] = (family["name"], category)
tags = family.get("focusTags") or []
tag_of_id = {tag["id"]: tag["slug"] for tag in tags}
specs[slug] = {
tag["slug"]: (
tag["name"],
aliases(tag.get("displayValue"), *(sub.get("displayValue") or sub["name"]
for sub in tag.get("focusSubTags") or [])),
)
for tag in tags
}
# Titles exist at the family level AND nested inside each focus
# tag; software-engineer's useful ones are all nested.
all_titles = list(family.get("jobTitles") or [])
for tag in tags:
all_titles += tag.get("jobTitles") or []
titles[slug] = {}
title_spec[slug] = {}
for title in all_titles:
titles[slug][title["slug"]] = (
title["name"], aliases(*(title.get("aliases") or [])))
if tag_of_id.get(title.get("focusTagId")):
title_spec[slug][title["slug"]] = tag_of_id[title["focusTagId"]]
def mapping(name: str, table: dict) -> str:
lines = [f"{name} = {{"]
for slug in sorted(table):
value = table[slug]
if isinstance(value, dict):
inner = ", ".join(
f"{k!r}: ({v[0]!r}, {v[1]!r})" if isinstance(v, tuple) else f"{k!r}: {v!r}"
for k, v in sorted(value.items()))
lines.append(f" {slug!r}: {{{inner}}},")
else:
lines.append(f" {slug!r}: {value!r},")
return "\n".join(lines + ["}", ""])
return (HEADER.format(date=lib.today_utc().isoformat())
+ mapping("ROLES", roles) + "\n"
+ mapping("SPECIALIZATIONS", specs) + "\n"
+ mapping("TITLES", titles) + "\n"
+ mapping("TITLE_TO_SPEC", title_spec))
def main() -> int:
families = catalog()
text = emit(families)
if OUT.exists() and OUT.read_text(encoding="utf-8") == text:
print(f"{OUT.name}: unchanged, {sum(len(v) for v in families.values())} roles")
return 0
OUT.write_text(text, encoding="utf-8")
print(f"{OUT.name}: {sum(len(v) for v in families.values())} roles across "
f"{len(families)} categories")
return 0
if __name__ == "__main__":
sys.exit(main())