返回 last30days-skill
employer_site.py
根目录 / skills / last30days / scripts / lib / employer_site.py
1 """A person's bio, read from their employer's own website. No key needed.
2
3 The lane works out the employer's site (an explicit domain, a work email's
4 domain, or the site the company lookup gives for an employer name), then
5 tries the pages a company usually lists its people on (``/team``,
6 ``/about``, ``/leadership`` ...) and guesses at a page of the person's own
7 (``/team/dana-okafor``). A caller with a web search backend can pass one
8 site-scoped search as ``site_search``.
9
10 A page counts only when the person's full name appears on it as a run of
11 whole words. What is read is the block around the name (the card, list item,
12 section or article that holds it): its text, a title line, and the links in
13 that block, so the company's own header and footer links are never taken
14 for the person's. Every fetch stays on the employer's site and off private
15 networks, redirects included. Page text is remote content: the bio is
16 truncated and fenced as untrusted before the host reads it.
17 """
18
19 from __future__ import annotations
20
21 import re
22 import time
23 import unicodedata
24 from html.parser import HTMLParser
25 from typing import Any, Callable, Iterable
26 from urllib.parse import urljoin, urlparse
27
28 from . import company_resolve, health, http, jobs, linkedin, log, person, public_host, rerank
29
30 # Pages a company usually lists its people on, tried in this order.
31 TEAM_PATHS = ("/team", "/about", "/about-us", "/leadership", "/people", "/company")
32 # Sections under which a person may have a page of their own.
33 PERSON_PATH_PREFIXES = ("/team", "/people")
34 # Wall time for the whole lane when the caller gives no deadline.
35 DEFAULT_BUDGET_SECONDS = 20.0
36 PAGE_TIMEOUT_SECONDS = 8
37 # Pages from the site-scoped search tried at most.
38 SEARCH_RESULT_LIMIT = 2
39 # Characters of bio text the host sees, before the untrusted fence.
40 BIO_CHAR_LIMIT = 1500
41 TITLE_CHAR_LIMIT = 100
42 # Characters of page text kept on each side of the name when no block holds it.
43 WINDOW_CHARS = 600
44 # HTML read from one page.
45 PAGE_CHAR_LIMIT = 500_000
46
47 FOUND = "found"
48 NOT_FOUND = "not found"
49 FAILED = "failed"
50 TIMEOUT = "timeout"
51
52 _VOID_TAGS = frozenset({
53 "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
54 "source", "track", "wbr",
55 })
56 # Content never read: code, styling and the page's head.
57 _SKIP_TAGS = frozenset({"script", "style", "noscript", "template", "svg", "head"})
58 # Site-wide chrome: a name or link there is the company's, not the person's.
59 _CHROME_TAGS = frozenset({"header", "footer", "nav", "aside"})
60 # Elements that hold one person's card on a team page.
61 _BLOCK_TAGS = frozenset({"article", "li", "section", "div", "figure", "tr", "td", "dd"})
62 # Repeated siblings of these mean a list of people, not one person's card.
63 _ENTRY_TAGS = frozenset({"h1", "h2", "h3", "h4", "h5", "h6", "li", "article", "figure", "tr"})
64 # Past these, the name has no block of its own.
65 _PAGE_TAGS = frozenset({"main", "body", "html", "root"})
66
67
68 class _Node:
69 __slots__ = ("tag", "attrs", "children", "parent")
70
71 def __init__(self, tag: str, attrs: dict[str, str], parent: "_Node | None"):
72 self.tag = tag
73 self.attrs = attrs
74 self.children: list[_Node | str] = []
75 self.parent = parent
76
77
78 class _TreeBuilder(HTMLParser):
79 """A forgiving element tree: unclosed tags close with their parent, and
80 a stray end tag is ignored."""
81
82 def __init__(self) -> None:
83 super().__init__(convert_charrefs=True)
84 self.root = _Node("root", {}, None)
85 self._current = self.root
86 self._skipping = 0
87
88 def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
89 if self._skipping or tag in _SKIP_TAGS:
90 if tag in _SKIP_TAGS and tag not in _VOID_TAGS:
91 self._skipping += 1
92 return
93 node = _Node(tag, {name: value or "" for name, value in attrs}, self._current)
94 self._current.children.append(node)
95 if tag not in _VOID_TAGS:
96 self._current = node
97
98 def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
99 if self._skipping or tag in _SKIP_TAGS:
100 return
101 self._current.children.append(_Node(tag, {name: value or "" for name, value in attrs}, self._current))
102
103 def handle_endtag(self, tag: str) -> None:
104 if self._skipping:
105 if tag in _SKIP_TAGS:
106 self._skipping -= 1
107 return
108 node: _Node | None = self._current
109 while node is not None and node is not self.root and node.tag != tag:
110 node = node.parent
111 if node is not None and node is not self.root and node.parent is not None:
112 self._current = node.parent
113
114 def handle_data(self, data: str) -> None:
115 if not self._skipping:
116 self._current.children.append(data)
117
118
119 def _parse(html: str) -> _Node:
120 builder = _TreeBuilder()
121 try:
122 builder.feed(html[:PAGE_CHAR_LIMIT])
123 builder.close()
124 except Exception: # noqa: BLE001 - a malformed page is a page with less on it
125 pass
126 return builder.root
127
128
129 def _segments(node: _Node, in_anchor: bool = False) -> Iterable[tuple[str, bool]]:
130 """Each run of text under ``node``, whitespace collapsed, and whether it
131 is a link's text."""
132 for child in node.children:
133 if isinstance(child, str):
134 text = " ".join(child.split())
135 if text:
136 yield text, in_anchor
137 elif child.tag not in _CHROME_TAGS:
138 yield from _segments(child, in_anchor or child.tag == "a")
139
140
141 def _text(node: _Node) -> str:
142 return " ".join(text for text, _anchor in _segments(node))
143
144
145 def _tokens(text: str) -> list[str]:
146 return linkedin._normalize_name(text).split()
147
148
149 def _has_name(node: _Node, name: list[str], memo: dict[int, bool]) -> bool:
150 key = id(node)
151 if key not in memo:
152 memo[key] = linkedin._token_run(name, _tokens(_text(node)))
153 return memo[key]
154
155
156 def _deepest_with_name(node: _Node, name: list[str], memo: dict[int, bool]) -> _Node | None:
157 """The innermost element outside the site's chrome whose text holds the
158 full name, or None when the page does not name the person."""
159 if node.tag in _CHROME_TAGS or not _has_name(node, name, memo):
160 return None
161 for child in node.children:
162 if isinstance(child, _Node):
163 found = _deepest_with_name(child, name, memo)
164 if found is not None:
165 return found
166 return node
167
168
169 def _person_block(holder: _Node, name: list[str]) -> _Node | None:
170 """The nearest card-like element around the name that says more than the
171 name, or None when only the whole page does."""
172 node: _Node | None = holder
173 while node is not None and node.tag not in _PAGE_TAGS:
174 if node.tag in _BLOCK_TAGS and len(_tokens(_text(node))) > len(name):
175 return node
176 node = node.parent
177 return None
178
179
180 def _shared_with_others(holder: _Node, block: _Node) -> bool:
181 """True when the block holds a list of people rather than one person: on
182 the way up from the name, an entry (heading, list item, card) has a
183 sibling entry of the same kind, so a link in the block may be a
184 colleague's."""
185 node = holder
186 while node is not block and node.parent is not None:
187 if node.tag in _ENTRY_TAGS and any(
188 isinstance(sibling, _Node) and sibling is not node and sibling.tag == node.tag
189 for sibling in node.parent.children
190 ):
191 return True
192 node = node.parent
193 return False
194
195
196 def _title_line(segments: list[tuple[str, bool]], name: list[str]) -> str:
197 """The short line after the name that reads as a job title, or ''."""
198 after = None
199 for index, (text, _anchor) in enumerate(segments):
200 tokens = _tokens(text)
201 if linkedin._token_run(name, tokens) or (tokens and tokens[-1] == name[-1]):
202 after = index
203 break
204 if after is None:
205 return ""
206 for text, anchor in segments[after + 1:]:
207 if anchor:
208 continue
209 words = text.split()
210 if 1 <= len(words) <= 12 and len(text) <= TITLE_CHAR_LIMIT and not text.endswith("."):
211 return _defang(text)
212 return ""
213 return ""
214
215
216 def _links(block: _Node, page_url: str, site_host: str) -> list[str]:
217 """Absolute links in the block that leave the employer's site."""
218 found: list[str] = []
219
220 def walk(node: _Node) -> None:
221 for child in node.children:
222 if not isinstance(child, _Node) or child.tag in _CHROME_TAGS:
223 continue
224 if child.tag == "a" and child.attrs.get("href"):
225 url = urljoin(page_url, child.attrs["href"].strip())
226 parsed = urlparse(url)
227 if (
228 parsed.scheme in ("http", "https") and parsed.hostname
229 and not jobs._same_site(parsed.hostname, site_host) and url not in found
230 ):
231 found.append(url)
232 walk(child)
233
234 walk(block)
235 return found
236
237
238 def _defang(text: str) -> str:
239 return rerank._defang_untrusted_fence(text)
240
241
242 def _fence(text: str) -> str:
243 """Truncate page text and fence it as untrusted data."""
244 text = " ".join(text.split())
245 if len(text) > BIO_CHAR_LIMIT:
246 text = text[: BIO_CHAR_LIMIT - 3].rstrip() + "..."
247 return f"<untrusted_content>\n{_defang(text)}\n</untrusted_content>"
248
249
250 def _window(page_text: str, name: list[str]) -> str:
251 """Page text around the first mention of the name."""
252 pattern = r"\W+".join(re.escape(token) for token in name)
253 match = re.search(rf"(?<![a-z0-9]){pattern}(?![a-z0-9])", page_text, re.I)
254 if match is None:
255 return page_text[: 2 * WINDOW_CHARS]
256 return page_text[max(0, match.start() - WINDOW_CHARS): match.end() + WINDOW_CHARS]
257
258
259 def _read_page(html: str, page_url: str, name: list[str], site_host: str) -> dict[str, Any] | None:
260 """The person's bio, title and links from one page, or None when the page
261 does not name them in full."""
262 root = _parse(html)
263 holder = _deepest_with_name(root, name, {})
264 if holder is None:
265 return None
266 block = _person_block(holder, name)
267 if block is None:
268 return {"title": "", "bio": _fence(_window(_text(root), name)), "links": []}
269 segments = list(_segments(block))
270 if _shared_with_others(holder, block):
271 # Several people share the block: keep the text near the name and
272 # take no links, since any of them may be a colleague's.
273 return {
274 "title": _title_line(segments, name),
275 "bio": _fence(_window(_text(block), name)),
276 "links": [],
277 }
278 return {
279 "title": _title_line(segments, name),
280 "bio": _fence(" ".join(text for text, _anchor in segments)),
281 "links": _links(block, page_url, site_host),
282 }
283
284
285 def _hostname(value: str) -> str:
286 value = (value or "").strip()
287 if "@" in value and "://" not in value:
288 value = value.rsplit("@", 1)[1]
289 if not value:
290 return ""
291 try:
292 host = urlparse(value if "://" in value else f"https://{value}").hostname or ""
293 except ValueError:
294 return ""
295 return host.lower().rstrip(".")
296
297
298 def _employer_host(
299 domain: str | None, email_domain: str | None, employer_name: str | None,
300 ) -> tuple[str, bool]:
301 """The employer's site host ('' when none is known) and whether looking
302 it up failed."""
303 host = _hostname(domain or "")
304 if host:
305 return host, False
306 host = _hostname(email_domain or "")
307 if host and not person.is_freemail_domain(host):
308 return host, False
309 if domain or email_domain or not (employer_name or "").strip():
310 return "", False
311 found = company_resolve.resolve_company(employer_name.strip(), listing=False)
312 if isinstance(found, company_resolve.FailedLookup):
313 return "", True
314 return _hostname(str(found.get("company_site") or "")), False
315
316
317 def _slug(full_name: str) -> str:
318 ascii_name = unicodedata.normalize("NFKD", full_name).encode("ascii", "ignore").decode("ascii")
319 return re.sub(r"[^a-z0-9]+", "-", ascii_name.lower()).strip("-")
320
321
322 def _candidates(host: str, full_name: str) -> list[str]:
323 base = f"https://{host}"
324 slug = _slug(full_name)
325 urls = [base + path for path in TEAM_PATHS]
326 if slug:
327 urls += [f"{base}{prefix}/{slug}" for prefix in PERSON_PATH_PREFIXES]
328 return urls
329
330
331 def _search_urls(site_search: Callable[[str], Any], host: str, full_name: str) -> list[str]:
332 """Same-site public pages from one site-scoped search."""
333 try:
334 results = site_search(f'site:{host.removeprefix("www.")} "{full_name}"') or []
335 except Exception as exc: # noqa: BLE001 - a search backend failing is not the lane failing
336 log.source_log("Employer", f"site search failed: {type(exc).__name__}: {exc}", tty_only=False)
337 return []
338 urls: list[str] = []
339 for result in results:
340 url = str((result.get("url") if isinstance(result, dict) else result) or "").strip()
341 if url and url not in urls and public_host.public_url(url, host):
342 urls.append(url)
343 if len(urls) >= SEARCH_RESULT_LIMIT:
344 break
345 return urls
346
347
348 def _fetch(url: str, host: str, deadline: float) -> tuple[str | None, bool]:
349 """The page at ``url`` and whether the request timed out. A guessed page
350 that is not there (403, 404, 410, or a redirect off the site) is no
351 failure of the run's; a timeout or a server error still is."""
352 remaining = deadline - time.monotonic()
353 if remaining <= 0:
354 return None, True
355 landed: list[str] = []
356 with http.expected_misses(403, 404, 410), http.tee_failures() as failures:
357 try:
358 text = http.get_text(
359 url, timeout=PAGE_TIMEOUT_SECONDS, retries=1, accept="text/html", retry_dns=False,
360 deadline_monotonic=time.monotonic() + min(remaining, PAGE_TIMEOUT_SECONDS),
361 landed=landed, redirect_guard=public_host.redirect_guard(url), public_only=True,
362 )
363 except UnicodeDecodeError:
364 text = None
365 timed_out = any(failure.outcome_state == health.TIMEOUT for failure in failures)
366 if text is not None and landed and not public_host.public_url(str(landed[-1]), host):
367 return None, timed_out
368 return text, timed_out
369
370
371 def _result(status: str, host: str, url: str = "", page: dict[str, Any] | None = None) -> dict[str, Any]:
372 page = page or {}
373 return {
374 "status": status,
375 "url": url,
376 "title": page.get("title", ""),
377 "bio": page.get("bio", ""),
378 "links": list(page.get("links", [])),
379 "domain": host,
380 }
381
382
383 def find_bio(
384 full_name: str,
385 *,
386 domain: str | None = None,
387 employer_name: str | None = None,
388 email_domain: str | None = None,
389 deadline_monotonic: float | None = None,
390 site_search: Callable[[str], Any] | None = None,
391 ) -> dict[str, Any]:
392 """The person's bio from their employer's site.
393
394 The site is ``domain`` (a host or URL) when given, else the domain of
395 ``email_domain`` (a domain or an address) unless it is a mailbox
396 provider's, else the official site the company lookup gives for
397 ``employer_name``. ``site_search(query)`` is optional: called at most
398 once, after the fixed pages miss, it returns URLs (or dicts with a
399 ``url``); only pages on the employer's site are read.
400
401 Returns ``status`` ("found", "not found", "failed" when the site could
402 not be looked up or is not a public host, "timeout" when the deadline
403 passed first), ``url`` of the page read, ``title``, ``bio`` (truncated
404 and fenced in ``<untrusted_content>``), ``links`` (the absolute,
405 off-site links in the person's own block) and ``domain``.
406 """
407 deadline = deadline_monotonic if deadline_monotonic is not None else time.monotonic() + DEFAULT_BUDGET_SECONDS
408 name = _tokens(full_name)
409 host, lookup_failed = _employer_host(domain, email_domain, employer_name)
410 if lookup_failed:
411 return _result(FAILED, "")
412 if not host or len(name) < 2:
413 return _result(NOT_FOUND, host)
414 if not public_host.public_url(f"https://{host}/", host):
415 log.source_log("Employer", f"{host} is not a public host; not fetched", tty_only=False)
416 return _result(FAILED, host)
417
418 tried: set[str] = set()
419
420 def read(urls: list[str]) -> dict[str, Any] | None:
421 for url in urls:
422 if url in tried:
423 continue
424 if time.monotonic() >= deadline:
425 return _result(TIMEOUT, host)
426 tried.add(url)
427 html, _timed_out = _fetch(url, host, deadline)
428 if html:
429 page = _read_page(html, url, name, host)
430 if page is not None:
431 return _result(FOUND, host, url, page)
432 return None
433
434 found = read(_candidates(host, full_name))
435 if found is not None:
436 return found
437 if site_search is not None and time.monotonic() < deadline:
438 found = read(_search_urls(site_search, host, full_name))
439 if found is not None:
440 return found
441 if time.monotonic() >= deadline:
442 return _result(TIMEOUT, host)
443 return _result(NOT_FOUND, host)
444
444 lines PYTHON