| 1 | """A bounded, role-unique digest of one company's job board. |
| 2 | |
| 3 | Job descriptions open with the same company text on every role, so the first |
| 4 | few hundred characters of each say nothing about that role. The digest keeps |
| 5 | what a role says that the rest of the board does not, for a few roles chosen by |
| 6 | how rare they are on that board. It works on the raw board rows from |
| 7 | ``lib.jobs`` and decides nothing about what a role means. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import re |
| 13 | from collections import Counter |
| 14 | from typing import Any |
| 15 | |
| 16 | from . import hiring_signals, jobs_teams |
| 17 | from .job_boilerplate import BOILERPLATE_MIN_ROLES # noqa: F401 (re-exported) |
| 18 | from .job_boilerplate import key as _key |
| 19 | from .job_boilerplate import role_sentences, shared_sentence_counts |
| 20 | # Roles in the digest, and role-unique characters kept for each. |
| 21 | DIGEST_MAX_ROLES = 40 |
| 22 | # Of those, how many may go to roles the run itself ranked highest (its ranked |
| 23 | # job postings and the roles its hiring themes name) when the rarity pick left |
| 24 | # them out. The rest stay with the rarest roles. |
| 25 | ENGINE_ROLE_SLOTS = 10 |
| 26 | # Of the rest, how many go first to roles matching the run's story terms, |
| 27 | # shared evenly by the terms that matched (at least two each). |
| 28 | STORY_ROLE_SLOTS = 8 |
| 29 | STORY_TERM_MIN_SLOTS = 2 |
| 30 | # On a board with more open roles than this, a place or a title word only one |
| 31 | # role has is common enough to say nothing, and earns no score. |
| 32 | RARITY_MAX_OPEN_ROLES = 500 |
| 33 | # A title tail shared by this many roles, on a large board, is a team cluster; |
| 34 | # the upper bound grows to 1% of the board. |
| 35 | CLUSTER_MIN_ROLES = 3 |
| 36 | CLUSTER_MAX_ROLES = 20 |
| 37 | DIGEST_ROLE_CHARS = 600 |
| 38 | # Ceiling for the whole rendered digest section: room for every role at its |
| 39 | # full text plus about 300 characters of title, department, location and URL. |
| 40 | DIGEST_MAX_CHARS = 36_000 |
| 41 | # Locations named on one entry before the rest are counted. |
| 42 | DIGEST_ENTRY_LOCATIONS = 3 |
| 43 | |
| 44 | def unreadable_job_site_line(name: str) -> str: |
| 45 | """What the run says about a company's job site it knows and cannot read.""" |
| 46 | return f"{name}'s job site can't be read automatically" |
| 47 | |
| 48 | |
| 49 | _TITLE_TERM = re.compile(r"[a-z][a-z0-9+#-]{2,}") |
| 50 | |
| 51 | |
| 52 | def _text(item: dict[str, Any]) -> str: |
| 53 | return str(item.get("description_blocks") or item.get("description") or "") |
| 54 | |
| 55 | |
| 56 | def _group(item: dict[str, Any]) -> tuple[str, str]: |
| 57 | return _key(item.get("title")), _key(item.get("department")) |
| 58 | |
| 59 | |
| 60 | def _role_key(item: dict[str, Any]) -> tuple[str, ...]: |
| 61 | """What makes two board rows the same role posted in more than one place. |
| 62 | |
| 63 | They share a title and a department, and they say the same thing: their |
| 64 | description text is equal. Rows with no text are told apart only when the |
| 65 | board lists a whole posting per row (``whole_posting``); then each row is |
| 66 | its own role. Other rows with no text merge on title and department, since |
| 67 | such a board lists one row per location and nothing else separates them. |
| 68 | """ |
| 69 | text = _key(_text(item)) |
| 70 | if text: |
| 71 | return (*_group(item), "text", text) |
| 72 | if item.get("whole_posting"): |
| 73 | return (*_group(item), "posting", str(item.get("url") or item.get("id") or "")) |
| 74 | return (*_group(item), "", "") |
| 75 | |
| 76 | |
| 77 | def distinct_roles(items: list[dict[str, Any]]) -> list[dict[str, Any]]: |
| 78 | """Group board rows into roles; ``_role_key`` says which rows are one role. |
| 79 | |
| 80 | Each role is ``{"item": first row, "locations": [...], "urls": [...]}``. |
| 81 | The first row stands for the role; the other rows only add their locations |
| 82 | and posting URLs. |
| 83 | """ |
| 84 | roles: dict[tuple[str, ...], dict[str, Any]] = {} |
| 85 | for item in items: |
| 86 | if not _key(item.get("title")): |
| 87 | continue |
| 88 | role = roles.setdefault(_role_key(item), {"item": item, "locations": [], "urls": []}) |
| 89 | if item.get("story_term") and not role.get("story_term"): |
| 90 | role["story_term"] = str(item["story_term"]) |
| 91 | role["story_rank"] = item.get("story_rank") |
| 92 | # A row a reader already merged across locations names them all itself. |
| 93 | for place in item.get("locations") or [item.get("location")]: |
| 94 | location = str(place or "").strip() |
| 95 | if location and location not in role["locations"]: |
| 96 | role["locations"].append(location) |
| 97 | url = str(item.get("url") or "").strip() |
| 98 | if url and url not in role["urls"]: |
| 99 | role["urls"].append(url) |
| 100 | return list(roles.values()) |
| 101 | |
| 102 | |
| 103 | def select_roles( |
| 104 | items: list[dict[str, Any]], *, limit: int = DIGEST_MAX_ROLES, |
| 105 | open_roles: int | None = None, teams: dict[str, Any] | None = None, |
| 106 | ) -> list[dict[str, Any]]: |
| 107 | """Pick the story roles, the named-team roles, then the roles rarest on |
| 108 | this board, at most ``limit``. |
| 109 | |
| 110 | Roles a story term matched (``story_term``) come first, up to |
| 111 | ``STORY_ROLE_SLOTS`` of them; see ``_story_picks``. Then, from ``teams`` |
| 112 | (``jobs_teams.named_teams``), the leads of teams no other title names |
| 113 | (tagged ``team_lead``) and each top team's newest role (tagged ``team``), |
| 114 | up to ``jobs_teams.LEAD_ROLE_SLOTS`` and ``jobs_teams.TEAM_ROLE_SLOTS``. |
| 115 | The rest are scored: |
| 116 | a role scores for sitting in a department no other role is in, for a |
| 117 | location no other row names, for a title word no other role uses, and for |
| 118 | a founding, leadership or specialized title. On a board of more than |
| 119 | ``RARITY_MAX_OPEN_ROLES`` open roles (``open_roles``, else the rows |
| 120 | given) the location and title word earn nothing. Ties go to the newest |
| 121 | role with a true posted date, then to board order. Two postings with one |
| 122 | title in one department count once toward how common that title's |
| 123 | department and words are. |
| 124 | """ |
| 125 | roles = distinct_roles(items) |
| 126 | rarity = (len(items) if open_roles is None else open_roles) <= RARITY_MAX_OPEN_ROLES |
| 127 | groups = {_group(role["item"]) for role in roles} |
| 128 | departments = Counter(department for _title, department in groups if department) |
| 129 | # Counted from the same places a role is shown with, so a place that is |
| 130 | # one role's first and several others' extra is not taken for rare. |
| 131 | locations = Counter( |
| 132 | _key(place) for item in items |
| 133 | for place in item.get("locations") or [item.get("location")] if _key(place) |
| 134 | ) |
| 135 | terms = Counter( |
| 136 | term for title in {title for title, _department in groups} |
| 137 | for term in set(_TITLE_TERM.findall(title)) |
| 138 | ) |
| 139 | |
| 140 | places = { |
| 141 | hiring_signals.place_key(place) for item in items |
| 142 | for place in item.get("locations") or [item.get("location")] if _key(place) |
| 143 | } |
| 144 | |
| 145 | # On a board too large for one-offs to mean anything, a small team named |
| 146 | # in several titles ("..., Air Manufacturing Innovation") is the signal. |
| 147 | tails = Counter() if rarity else Counter( |
| 148 | tail.lower() for tail in ( |
| 149 | hiring_signals._specialization(title, places=places) |
| 150 | for title in {title for title, _department in groups} |
| 151 | ) if tail |
| 152 | ) |
| 153 | cluster_max = max(CLUSTER_MAX_ROLES, (open_roles or len(items)) // 100) |
| 154 | |
| 155 | def clustered(item: dict[str, Any]) -> bool: |
| 156 | tail = hiring_signals._specialization(str(item.get("title") or ""), places=places) |
| 157 | return bool(tail) and CLUSTER_MIN_ROLES <= tails[tail.lower()] <= cluster_max |
| 158 | |
| 159 | def board_size_score(role: dict[str, Any]) -> int: |
| 160 | item = role["item"] |
| 161 | if not rarity: |
| 162 | return 3 * clustered(item) |
| 163 | return ( |
| 164 | 3 * any(locations[_key(location)] == 1 for location in role["locations"]) |
| 165 | + 2 * any( |
| 166 | terms[term] == 1 |
| 167 | for term in _TITLE_TERM.findall(_key(item.get("title"))) |
| 168 | ) |
| 169 | ) |
| 170 | |
| 171 | def score(role: dict[str, Any]) -> int: |
| 172 | item = role["item"] |
| 173 | department = departments.get(_key(item.get("department")), 0) |
| 174 | flags = hiring_signals._title_flags(str(item.get("title") or ""), places=places) |
| 175 | return ( |
| 176 | 3 * (department == 1) |
| 177 | + 1 * (department == 2) |
| 178 | + board_size_score(role) |
| 179 | + 4 * ("founding" in flags) |
| 180 | + 2 * ("leadership" in flags) |
| 181 | + 1 * ("specialized" in flags) |
| 182 | ) |
| 183 | |
| 184 | def posted(role: dict[str, Any]) -> str: |
| 185 | item = role["item"] |
| 186 | return str(item.get("date") or "") if item.get("posted_date_true") else "" |
| 187 | |
| 188 | story = _story_picks(roles, min(limit, STORY_ROLE_SLOTS)) |
| 189 | taken = set(story) |
| 190 | named = _team_picks(roles, teams, taken) |
| 191 | taken.update(named) |
| 192 | order = sorted( |
| 193 | (index for index in range(len(roles)) if index not in taken), |
| 194 | key=lambda index: (-score(roles[index]), _reverse(posted(roles[index])), index), |
| 195 | ) |
| 196 | return [roles[index] for index in [*story, *named, *order][:limit]] |
| 197 | |
| 198 | |
| 199 | def _team_picks( |
| 200 | roles: list[dict[str, Any]], teams: dict[str, Any] | None, taken: set[int], |
| 201 | ) -> list[int]: |
| 202 | """Indexes of the named-team leads, then each top team's newest role, |
| 203 | tagging each role with what it stands for. A role already taken (a story |
| 204 | match) keeps its slot and is not counted twice.""" |
| 205 | if not teams: |
| 206 | return [] |
| 207 | where = {_role_key(role["item"]): index for index, role in enumerate(roles)} |
| 208 | picks: list[int] = [] |
| 209 | |
| 210 | def take(row: dict[str, Any], tag: str, value: Any, slots: int, used: list[int]) -> None: |
| 211 | index = where.get(_role_key(row)) if _key(row.get("title")) else None |
| 212 | if index is None or index in taken or index in picks or len(used) >= slots: |
| 213 | return |
| 214 | roles[index][tag] = value |
| 215 | picks.append(index) |
| 216 | used.append(index) |
| 217 | |
| 218 | leads: list[int] = [] |
| 219 | for row in teams.get("lead_items") or []: |
| 220 | take(row, "team_lead", True, jobs_teams.LEAD_ROLE_SLOTS, leads) |
| 221 | members: list[int] = [] |
| 222 | for team, row in zip(teams.get("teams") or [], teams.get("team_items") or []): |
| 223 | take(row, "team", {"name": team["name"], "roles": team["roles"]}, jobs_teams.TEAM_ROLE_SLOTS, members) |
| 224 | return picks |
| 225 | |
| 226 | |
| 227 | def _story_picks(roles: list[dict[str, Any]], slots: int) -> list[int]: |
| 228 | """Indexes of the story roles that take the reserved slots. |
| 229 | |
| 230 | The slots are shared evenly by the terms that matched a role, at least |
| 231 | ``STORY_TERM_MIN_SLOTS`` each, in the order the terms first matched. Each |
| 232 | term's roles go in the order the board's search returned them |
| 233 | (``story_rank``), else board order. A term with fewer roles than its |
| 234 | share passes the unused slots on to the terms that have more. |
| 235 | """ |
| 236 | queues: dict[str, list[int]] = {} |
| 237 | ranked = sorted( |
| 238 | (index for index, role in enumerate(roles) if role.get("story_term")), |
| 239 | key=lambda index: ( |
| 240 | roles[index].get("story_rank") is None, roles[index].get("story_rank") or 0, index, |
| 241 | ), |
| 242 | ) |
| 243 | for index in ranked: |
| 244 | queues.setdefault(roles[index]["story_term"], []).append(index) |
| 245 | if not queues or slots <= 0: |
| 246 | return [] |
| 247 | share = max(STORY_TERM_MIN_SLOTS, slots // len(queues)) |
| 248 | counts: dict[str, int] = {} |
| 249 | left = slots |
| 250 | for term, queue in queues.items(): |
| 251 | counts[term] = min(share, len(queue), left) |
| 252 | left -= counts[term] |
| 253 | # Unused shares, one slot at a time to each term with roles left. |
| 254 | while left > 0 and any(counts[term] < len(queue) for term, queue in queues.items()): |
| 255 | for term, queue in queues.items(): |
| 256 | if left > 0 and counts[term] < len(queue): |
| 257 | counts[term] += 1 |
| 258 | left -= 1 |
| 259 | return [index for term, queue in queues.items() for index in queue[:counts[term]]] |
| 260 | |
| 261 | |
| 262 | def add_engine_roles( |
| 263 | digest: dict[str, Any], |
| 264 | items: list[dict[str, Any]], |
| 265 | urls: list[str], |
| 266 | *, |
| 267 | slots: int = ENGINE_ROLE_SLOTS, |
| 268 | limit: int = DIGEST_MAX_ROLES, |
| 269 | ) -> dict[str, Any]: |
| 270 | """Return ``digest`` with the roles the run ranked highest kept in it. |
| 271 | |
| 272 | ``urls`` are posting URLs in the run's own order of importance and |
| 273 | ``items`` the board rows the digest was built from. The first ``slots`` |
| 274 | ranked roles on the board are reserved a place: one the digest already |
| 275 | lists is marked ``engine`` where it stands, and the others are added at |
| 276 | the front with their role-unique text. The places they need are given up |
| 277 | by the rarity picks that are not reserved, rarest kept longest, so the |
| 278 | digest never holds more than ``limit`` roles and never loses a reserved |
| 279 | one. A ranked role past the reserved places is left as it is, and a URL |
| 280 | that is not on the board is passed over. An added role the board gave no |
| 281 | text for is counted in ``note``. |
| 282 | """ |
| 283 | entries = [dict(entry) for entry in digest.get("roles") or []] |
| 284 | listed = { |
| 285 | url: entry |
| 286 | for entry in entries |
| 287 | for url in (entry.get("url"), *(entry.get("urls") or [])) if url |
| 288 | } |
| 289 | by_url = {url: role for role in distinct_roles(items) for url in role["urls"]} |
| 290 | picked: list[dict[str, Any]] = [] |
| 291 | reserved = 0 |
| 292 | for url in urls: |
| 293 | if reserved >= slots: |
| 294 | break |
| 295 | if url in listed: |
| 296 | if not listed[url].get("engine"): |
| 297 | listed[url]["engine"] = True |
| 298 | reserved += 1 |
| 299 | continue |
| 300 | role = by_url.get(url) |
| 301 | if role is None or any(role is chosen for chosen in picked): |
| 302 | continue |
| 303 | picked.append(role) |
| 304 | reserved += 1 |
| 305 | added = build_digest(items, picked)["roles"] if picked else [] |
| 306 | for entry in added: |
| 307 | entry["engine"] = True |
| 308 | # The unreserved rarity picks give up places from their end. |
| 309 | spare = max(0, limit - len(added) - sum(1 for entry in entries if entry.get("engine"))) |
| 310 | kept = [] |
| 311 | for entry in entries: |
| 312 | if entry.get("engine"): |
| 313 | kept.append(entry) |
| 314 | elif spare > 0: |
| 315 | kept.append(entry) |
| 316 | spare -= 1 |
| 317 | out = { |
| 318 | **digest, |
| 319 | "roles": [*added, *kept][:limit], |
| 320 | "engine_roles": reserved, |
| 321 | } |
| 322 | # A board that gives a role's text one call at a time (Workday) was asked |
| 323 | # only for the rarity picks, before anything was ranked. |
| 324 | bare = sum(1 for entry in added if not entry["text"]) |
| 325 | if bare: |
| 326 | note = ( |
| 327 | f"{bare} of the ranked roles listed first have no role text " |
| 328 | "(this board gives it one call per role, made before ranking)" |
| 329 | ) |
| 330 | out["note"] = f"{digest['note']}; {note}" if digest.get("note") else note |
| 331 | return out |
| 332 | |
| 333 | |
| 334 | def _reverse(date: str) -> tuple[int, ...]: |
| 335 | """Sort key that puts later ISO dates first and undated roles last.""" |
| 336 | return tuple(-ord(char) for char in date) if date else (1,) |
| 337 | |
| 338 | |
| 339 | def build_digest( |
| 340 | items: list[dict[str, Any]], selected: list[dict[str, Any]], |
| 341 | ) -> dict[str, Any]: |
| 342 | """Return the digest of ``selected`` roles against the whole board. |
| 343 | |
| 344 | Sentences are counted once per title in a department, then each selected |
| 345 | role keeps its sentences that fewer than ``BOILERPLATE_MIN_ROLES`` such |
| 346 | titles share, cut to ``DIGEST_ROLE_CHARS``. |
| 347 | """ |
| 348 | roles = distinct_roles(items) |
| 349 | shared = shared_sentence_counts( |
| 350 | (str(role["item"].get("title") or ""), str(role["item"].get("department") or ""), |
| 351 | _text(role["item"])) |
| 352 | for role in roles |
| 353 | ) |
| 354 | |
| 355 | entries: list[dict[str, Any]] = [] |
| 356 | for role in selected: |
| 357 | item = role["item"] |
| 358 | unique = " ".join(role_sentences(_text(item), shared)) |
| 359 | if len(unique) > DIGEST_ROLE_CHARS: |
| 360 | unique = unique[: DIGEST_ROLE_CHARS - 3].rstrip() + "..." |
| 361 | named = role["locations"][:DIGEST_ENTRY_LOCATIONS] |
| 362 | more = len(role["locations"]) - len(named) |
| 363 | entries.append({ |
| 364 | "title": str(item.get("title") or "").strip(), |
| 365 | "department": str(item.get("department") or "").strip(), |
| 366 | "location": "; ".join(named) + (f"; +{more} more" if more > 0 else ""), |
| 367 | "posted": str(item.get("date") or "") if item.get("posted_date_true") else "", |
| 368 | "url": str(item.get("url") or "").strip(), |
| 369 | # Every posting the entry stands for (one per location it merged). |
| 370 | "urls": list(role.get("urls") or []), |
| 371 | "text": unique, |
| 372 | }) |
| 373 | for tag in ("story_term", "team", "team_lead"): |
| 374 | if role.get(tag): |
| 375 | entries[-1][tag] = role[tag] |
| 376 | return {"distinct_roles": len(roles), "roles": entries} |
| 377 |