返回 last30days-skill
jobs_teams.py
根目录 / skills / last30days / scripts / lib / jobs_teams.py
1 """Named teams on a job board, read from its role titles.
2
3 A secret hiring signal is rarely one role. It is a team the press has not
4 named yet ("Applied Scientist, Fauna", "Head of UK, Ad Solutions") whose
5 name repeats across a handful of titles, or a head, GM or founding hire for
6 a team whose name no other title carries. Story terms cannot find these,
7 because nobody has written the story yet, so the board's own titles are read
8 for them instead.
9
10 A title's team is any segment after its first, split on commas, spaced
11 dashes, bars, slashes, colons and parentheses: "Robotics Software
12 Development Engineer, Fauna" names "fauna". Shifts, levels, contract types,
13 languages, legal tags, stores and places are not teams.
14 """
15
16 from __future__ import annotations
17
18 import math
19 import re
20 from collections import Counter, defaultdict
21 from typing import Any
22
23 TEAM_LINE_LIMIT = 12 # teams named on the digest's Named teams line
24 TEAM_ROLE_SLOTS = 8 # digest slots for one role of each top team
25 LEAD_ROLE_SLOTS = 6 # digest slots for leads of a team no other title names
26 TEAM_MIN_ROLES = 3
27 TEAM_MAX_ROLES = 60 # or 2% of the board, whichever is larger
28 LEAD_MAX_TITLES = 3 # a lead's team phrase is in at most this many titles
29
30 _SPLIT = re.compile(r"\s*(?:,|\s[-–|/]\s|\(|\)|:)\s*")
31 _WORD = re.compile(r"[a-z][a-z&]+")
32 _NOISE = re.compile(
33 r"(?:\b(?:shift|part[- ]time|full[- ]time|seasonal|temp(?:orary)?|intern(?:ship)?s?|"
34 r"co-op|apprentice|new grad|graduate|contract|remote|hybrid|on-?site|speaking|"
35 r"nationals?|citizen|clearance|bilingual|fluent|multiple openings|all levels|level|"
36 r"req|store|showroom|service center|outlet|dfo|airport|mall|w/m/d|m/f/d|m/w/d|"
37 r"f/m/d|h/f|f/h|evergreen|pipeline|talent community|\d{4})\b)"
38 r"|^(?:sr\.?|senior|staff|principal|lead|junior|jr\.?|associate|i{1,3}|iv|v|[a-z]{2,4}|\d+)$",
39 re.I,
40 )
41 _LEAD = re.compile(
42 r"\b(?:head|gm|general manager|director|vp|vice president|founding|lead|chief|"
43 r"product manager|program manager)\b", re.I,
44 )
45 _NOT_LEAD = re.compile(r"\b(?:assistant|coordinator|associate|specialist|technician|advisor|recruiter)\b", re.I)
46 _SENIOR = re.compile(r"\b(?:head|gm|general manager|vp|vice president|chief|founding|director)\b", re.I)
47
48
49 def _segments(title: str) -> list[str]:
50 return [part.strip(" .") for part in _SPLIT.split(title or "") if part and part.strip(" .")]
51
52
53 def _team_names(title: str, company: str, place_words: set[str]) -> list[str]:
54 names = []
55 for segment in _segments(title)[1:]:
56 if company:
57 # Strip ampersands directly joined (or spaced-joined) to the removed
58 # company name so "Cloud&AI" and "Cloud& AI&Data" collapse cleanly
59 # without touching unrelated "&" in the segment.
60 segment = re.sub(
61 rf"(?:&+\s*)?\b{re.escape(company)}\b(?:\s*&+)?", " ", segment, flags=re.I,
62 )
63 name = " ".join(segment.split()).strip(" -,.&").lower()
64 words = _WORD.findall(name)
65 if len(name) < 3 or not words or _NOISE.search(name):
66 continue
67 if all(word in place_words for word in words):
68 continue
69 names.append(name)
70 return names
71
72
73 def _posted(item: dict[str, Any]) -> str:
74 return str(item.get("date") or "") if item.get("posted_date_true") else ""
75
76
77 def named_teams(
78 items: list[dict[str, Any]], *, company: str, window_start: str,
79 ) -> dict[str, Any]:
80 """The board's named teams and the leads of its newest small teams.
81
82 ``teams``: up to ``TEAM_LINE_LIMIT`` of ``{"name", "roles", "new"}``,
83 the teams whose name is most nearly theirs alone on the board, most
84 posted in the window, and largest, in that order of weight. ``new`` is
85 the roles posted since ``window_start``, or None when the board gives no
86 true posted dates. ``team_items`` is each listed team's newest role.
87 ``lead_items``: up to ``LEAD_ROLE_SLOTS`` head, GM, director, founding,
88 lead or product-manager roles for a team phrase in at most
89 ``LEAD_MAX_TITLES`` titles, one per team, posted-in-window and senior
90 first.
91 """
92 titles = [str(item.get("title") or "") for item in items]
93 word_titles = Counter()
94 for title in titles:
95 word_titles.update(set(_WORD.findall(title.lower())))
96 place_words = {
97 word for item in items
98 for place in item.get("locations") or [item.get("location")]
99 for word in _WORD.findall(str(place or "").lower())
100 }
101 # One role posted in several places is one role: a team counts distinct
102 # (title, department) roles, each by its first row, the newest posting.
103 members: dict[str, list[dict[str, Any]]] = defaultdict(list)
104 seen_roles: dict[str, dict[tuple[str, str], dict[str, Any]]] = defaultdict(dict)
105 for item, title in zip(items, titles):
106 role = (" ".join(title.lower().split()), " ".join(str(item.get("department") or "").lower().split()))
107 for name in dict.fromkeys(_team_names(title, company, place_words)):
108 first = seen_roles[name].get(role)
109 if first is None:
110 seen_roles[name][role] = item
111 members[name].append(item)
112 elif _posted(item) > _posted(first):
113 members[name][members[name].index(first)] = item
114 seen_roles[name][role] = item
115
116 # "fauna robotics" (one role) is the "fauna" team: fold a name too small
117 # to stand alone into the shorter name it starts with, keeping each role
118 # once. A team big enough to stand alone ("autonomy systems validation")
119 # stays itself rather than vanishing into a broad word ("autonomy").
120 for name in sorted(members, key=len):
121 if len(members[name]) >= TEAM_MIN_ROLES:
122 continue
123 words = name.split(" ")
124 base = next((
125 prefix for prefix in (" ".join(words[:cut]) for cut in range(1, len(words)))
126 if prefix in members
127 ), None)
128 if base is not None:
129 seen = {id(row) for row in members[base]}
130 members[base].extend(row for row in members[name] if id(row) not in seen)
131
132 position = {id(item): index for index, item in enumerate(items)}
133 size_cap = max(TEAM_MAX_ROLES, len(items) // 50)
134 scored = []
135 for name, rows in members.items():
136 if not TEAM_MIN_ROLES <= len(rows) <= size_cap:
137 continue
138 words = _WORD.findall(name)
139 rarest = max(1, min((word_titles[word] for word in words), default=1))
140 own = min(1.0, len(rows) / rarest)
141 dated = [_posted(row) for row in rows if _posted(row)]
142 new = sum(day >= window_start for day in dated) if dated else None
143 share = new / len(dated) if dated else 0.5
144 scored.append((own * 2 + share * 2 + min(math.log2(len(rows)), 4) / 2, name, rows, new))
145 scored.sort(key=lambda entry: (-entry[0], entry[1]))
146 teams, team_items = [], []
147 for _score, name, rows, new in scored:
148 teams.append({"name": name, "roles": len(rows), "new": new})
149 team_items.append(max(rows, key=lambda row: (_posted(row), -position[id(row)])))
150 if len(teams) == TEAM_LINE_LIMIT:
151 break
152
153 lowered = [title.lower() for title in titles]
154 leads: list[tuple[tuple, str, dict[str, Any]]] = []
155 for name, rows in members.items():
156 # Checked cheapest first: a name in more titles than a lead's team
157 # may be, or with no lead role, never needs the phrase count.
158 if len(rows) > LEAD_MAX_TITLES:
159 continue
160 candidates = []
161 for row in rows:
162 role = _segments(str(row.get("title") or ""))[:1]
163 if role and _LEAD.search(role[0]) and not _NOT_LEAD.search(role[0]):
164 candidates.append((row, role))
165 if not candidates:
166 continue
167 phrase_titles = sum(name in title for title in lowered)
168 if phrase_titles > LEAD_MAX_TITLES:
169 continue
170 for row, role in candidates:
171 posted = _posted(row)
172 key = (
173 posted >= window_start if posted else False,
174 bool(_SENIOR.search(role[0])),
175 posted,
176 -phrase_titles,
177 )
178 leads.append((key, name, row))
179 leads.sort(key=lambda entry: entry[0], reverse=True)
180 lead_items, lead_teams = [], set()
181 for _key, name, row in leads:
182 if name in lead_teams or any(row is chosen for chosen in lead_items):
183 continue
184 lead_teams.add(name)
185 lead_items.append(row)
186 if len(lead_items) == LEAD_ROLE_SLOTS:
187 break
188 return {"teams": teams, "team_items": team_items, "lead_items": lead_items}
189
189 lines PYTHON