返回 last30days-skill
person_linkedin.py
根目录 / skills / last30days / scripts / lib / person_linkedin.py
1 """Find and verify a person's LinkedIn profile for a person run.
2
3 Order of trust:
4
5 1. A ``--linkedin`` URL the user supplied is an anchor as given. Its profile
6 is read for facts; if its current employer differs from ``--employer``
7 the mismatch is recorded, since people change jobs.
8 2. With a Deepline key and an Exa key, an Exa people search on the name and
9 employer (never any part of an email) proposes ``linkedin.com/in/`` URLs.
10 Only results whose text names the employer are read, so a namesake costs
11 nothing.
12 3. A Deepline name lookup, by name plus employer, or by the full email when
13 there is no employer.
14
15 A looked-up URL becomes an anchor only when the profile read shows a current
16 or recent position at the employer (by name or company website), or at the
17 work email's domain, or when the lookup found it from the email itself. A
18 rejected candidate leaves nothing behind. Without a Deepline key the
19 ScrapeCreators profile reader can read a supplied URL when LinkedIn is opted
20 in or the URL was passed; it never looks a URL up and never reports a role.
21
22 Every outcome lands on the ``PersonContext``: ``linkedin_status``,
23 ``match_basis`` in plain words, ``linkedin_url``, ``anchors`` and ``profile``.
24 """
25
26 from __future__ import annotations
27
28 import re
29 import time
30 from datetime import date
31 from typing import Iterable
32 from urllib.parse import urlsplit
33
34 from . import company_names, deepline, grounding, linkedin, log
35 from . import person
36 from .person import PersonContext, normalize_linkedin_url
37
38 # Exa people results read for candidates.
39 EXA_RESULT_COUNT = 5
40 # The free pre-search gets at most this long, and runs only when enough of the
41 # shared deadline is left for the paid profile read after it.
42 EXA_SECONDS = 15.0
43 # History entries, newest first, that count as a recent position.
44 RECENT_POSITIONS = 3
45 # A past position counts only when it ended within this many years.
46 RECENT_POSITION_YEARS = 2
47 # Current-role employers added as anchors from an anchored profile.
48 MAX_EMPLOYER_ANCHORS = 3
49
50 SUPPLIED_BASIS = "LinkedIn URL supplied by user"
51 SELF_REPORTED_BASIS = "profile employer is self-reported"
52 EMAIL_LOOKUP_BASIS = "LinkedIn profile found by email lookup"
53
54
55 def _log(msg: str) -> None:
56 log.source_log("Person", msg, tty_only=False)
57
58
59 def linkedin_opted_in(config: dict, requested_sources: Iterable[str] | None = None) -> bool:
60 """True when the user opted into LinkedIn (INCLUDE_SOURCES or --search)."""
61 include = {
62 token.strip()
63 for token in str(config.get("INCLUDE_SOURCES") or "").lower().split(",")
64 if token.strip()
65 }
66 return "linkedin" in include or "linkedin" in set(requested_sources or ())
67
68
69 def scrapecreators_allowed(
70 ctx: PersonContext, config: dict, requested_sources: Iterable[str] | None = None,
71 ) -> bool:
72 """The ScrapeCreators fallback: no Deepline key, a ScrapeCreators key, and
73 LinkedIn opted in or a URL supplied (which is consent to read that one)."""
74 if deepline.is_available(config) or not str(config.get("SCRAPECREATORS_API_KEY") or "").strip():
75 return False
76 return bool(ctx.linkedin_url) or linkedin_opted_in(config, requested_sources)
77
78
79 def anchor_supplied_url(ctx: PersonContext) -> None:
80 """Anchor a user-supplied URL. No network; safe to call before any lookup."""
81 if ctx.linkedin_url:
82 ctx.add_anchor(ctx.linkedin_url)
83 if SUPPLIED_BASIS not in ctx.match_basis:
84 ctx.match_basis.append(SUPPLIED_BASIS)
85 ctx.identity_weak = False
86
87
88 # -- matching ------------------------------------------------------------------
89
90
91 def _host(value: str) -> str:
92 text = (value or "").strip()
93 if not text:
94 return ""
95 try:
96 host = urlsplit(text if "://" in text else f"https://{text}").hostname or ""
97 except ValueError:
98 return ""
99 host = host.lower().rstrip(".")
100 return host[4:] if host.startswith("www.") else host
101
102
103 def _names_match(company: str, employer: str) -> bool:
104 """Equal name keys, or one key a whole-word run inside the other."""
105 a, b = company_names.name_key(company), company_names.name_key(employer)
106 if not a or not b:
107 return False
108 if a == b:
109 return True
110 short, long = (a, b) if len(a) < len(b) else (b, a)
111 return bool(re.search(rf"(?<!\w){re.escape(short)}(?!\w)", long))
112
113
114 def _role_match(role: dict, ctx: PersonContext) -> str:
115 """What about this role matches the person's anchors, or ""."""
116 company = str(role.get("company") or "")
117 if ctx.employer_name and _names_match(company, ctx.employer_name):
118 return ctx.employer_name
119 website = _host(str(role.get("company_website") or ""))
120 for domain in (ctx.employer_domain, ctx.email_domain):
121 if person.same_or_subdomain(website, domain):
122 return domain
123 return ""
124
125
126 def _ended_recently(role: dict, today: date | None = None) -> bool:
127 """True when the role is ongoing or ended within RECENT_POSITION_YEARS. A
128 role whose end cannot be dated does not count: an old job at the same
129 employer must not confirm a namesake."""
130 end = str(role.get("end_date") or "").strip().lower()
131 if end in ("present", "current", "now"):
132 return True
133 years = [int(y) for y in re.findall(r"(?<!\d)((?:19|20)\d{2})(?!\d)", end)]
134 if not years:
135 return False
136 today = today or date.today()
137 return max(years) >= today.year - RECENT_POSITION_YEARS
138
139
140 def _verify(profile: dict, ctx: PersonContext) -> str:
141 """A plain-words basis when a current or recent position matches, else ""."""
142 for role in profile.get("current_roles") or []:
143 matched = _role_match(role, ctx)
144 if matched:
145 return f"profile current employer matches {matched}"
146 for role in (profile.get("history") or [])[:RECENT_POSITIONS]:
147 if not _ended_recently(role):
148 continue
149 matched = _role_match(role, ctx)
150 if matched:
151 return f"profile recent position matches {matched}"
152 return ""
153
154
155 # -- context writes ------------------------------------------------------------
156
157
158 def _store_profile(ctx: PersonContext, profile: dict, source: str) -> None:
159 ctx.profile = {
160 "source": source,
161 "headline": profile.get("headline") or "",
162 "location": profile.get("location") or "",
163 "current_roles": list(profile.get("current_roles") or []),
164 "history": list(profile.get("history") or []),
165 "websites": list(profile.get("websites") or []),
166 }
167 if profile.get("posts"):
168 ctx.profile["posts"] = list(profile["posts"])
169
170
171 def _anchor_profile(ctx: PersonContext, url: str, profile: dict | None, source: str) -> None:
172 ctx.linkedin_url = url
173 ctx.add_anchor(url)
174 ctx.identity_weak = False
175 if profile is None:
176 return
177 _store_profile(ctx, profile, source)
178 employers = [
179 str(role.get("company") or "").strip()
180 for role in profile.get("current_roles") or []
181 if str(role.get("company") or "").strip()
182 ]
183 for company in employers[:MAX_EMPLOYER_ANCHORS]:
184 ctx.add_anchor(company)
185 if ctx.employer_name and employers and not any(
186 _names_match(company, ctx.employer_name) for company in employers
187 ):
188 ctx.linkedin_mismatch = (
189 f"LinkedIn lists current employer {', '.join(employers[:MAX_EMPLOYER_ANCHORS])}, "
190 f"not {ctx.employer_name}"
191 )
192
193
194 def _canonical(url: str | None) -> str:
195 try:
196 return normalize_linkedin_url(url or "")
197 except ValueError:
198 return ""
199
200
201 # -- lanes -----------------------------------------------------------------
202
203
204 def _read_supplied(ctx, config, client, deadline, requested_sources) -> None:
205 if client is not None:
206 result = client.get_profile(ctx.linkedin_url, deadline_monotonic=deadline)
207 if result["status"] != deepline.OK:
208 ctx.set_linkedin_status(person.LINKEDIN_FAILED)
209 return
210 _anchor_profile(ctx, ctx.linkedin_url, result["data"], "deepline")
211 ctx.set_linkedin_status(person.LINKEDIN_CHECKED)
212 return
213 if scrapecreators_allowed(ctx, config, requested_sources):
214 result = linkedin.read_profile(
215 ctx.linkedin_url, str(config["SCRAPECREATORS_API_KEY"]).strip(),
216 deadline_monotonic=deadline,
217 )
218 if result["status"] != "ok":
219 ctx.set_linkedin_status(person.LINKEDIN_FAILED)
220 return
221 _store_profile(ctx, result["data"], "scrapecreators")
222 ctx.set_linkedin_status(person.LINKEDIN_CHECKED)
223 return
224 ctx.set_linkedin_status(person.LINKEDIN_NO_KEY)
225
226
227 def _exa_candidates(ctx: PersonContext, config: dict, deadline: float | None = None) -> list[str]:
228 """LinkedIn profile URLs from an Exa people search whose result text names
229 the employer. The query is the name and employer only."""
230 key = grounding.exa_api_key(config)
231 if not key or not ctx.employer_name:
232 return []
233 exa_deadline = time.monotonic() + EXA_SECONDS
234 if deadline is not None:
235 if deadline - time.monotonic() < EXA_SECONDS + deepline.MIN_ATTEMPT_SECONDS:
236 return []
237 exa_deadline = min(exa_deadline, deadline)
238 try:
239 results, _artifact = grounding.exa_people_search(
240 f"{ctx.full_name} {ctx.employer_name}", key, count=EXA_RESULT_COUNT,
241 deadline_monotonic=exa_deadline, retries=1,
242 )
243 except Exception as exc: # noqa: BLE001 - a free pre-search failing just skips it
244 _log(f"Exa people search failed: {type(exc).__name__}")
245 return []
246 employer_key = company_names.name_key(ctx.employer_name)
247 urls: list[str] = []
248 for result in results:
249 url = _canonical(str(result.get("url") or ""))
250 if not url or url in urls:
251 continue
252 text = f"{result.get('title') or ''} {result.get('snippet') or ''}"
253 key_text = company_names.name_key(text)
254 named = bool(employer_key) and bool(
255 re.search(rf"(?<!\w){re.escape(employer_key)}(?!\w)", key_text)
256 )
257 if named or (ctx.employer_domain and ctx.employer_domain in text.lower()):
258 urls.append(url)
259 return urls
260
261
262 def _lookup(ctx: PersonContext, client, deadline) -> tuple[str, bool, bool]:
263 """(candidate URL or "", found by email, lookup failed)."""
264 if ctx.employer_name or ctx.employer_domain:
265 result = client.find_profiles(
266 deadline_monotonic=deadline, full_name=ctx.full_name,
267 company_name=ctx.employer_name or None, company_domain=ctx.employer_domain or None,
268 )
269 by_email = False
270 elif ctx.email:
271 result = client.find_profiles(
272 deadline_monotonic=deadline, full_name=ctx.full_name, email=ctx.email,
273 )
274 by_email = True
275 else:
276 return "", False, False
277 if result["status"] != deepline.OK:
278 return "", by_email, True
279 return _canonical((result["data"] or {}).get("linkedin_url")), by_email, False
280
281
282 def _look_up(ctx, config, client, deadline) -> None:
283 rejected = failed = False
284 read: dict[str, dict | None] = {}
285
286 def read_profile(url: str) -> dict | None:
287 nonlocal failed
288 if url not in read:
289 result = client.get_profile(url, deadline_monotonic=deadline)
290 read[url] = result["data"] if result["status"] == deepline.OK else None
291 failed = failed or read[url] is None
292 return read[url]
293
294 for url in _exa_candidates(ctx, config, deadline)[:1]:
295 profile = read_profile(url)
296 if profile is None:
297 continue
298 basis = _verify(profile, ctx)
299 if basis:
300 _anchor_profile(ctx, url, profile, "deepline")
301 ctx.match_basis += [basis, SELF_REPORTED_BASIS]
302 ctx.set_linkedin_status(person.LINKEDIN_CHECKED)
303 return
304 rejected = True
305
306 url, by_email, lookup_failed = _lookup(ctx, client, deadline)
307 failed = failed or lookup_failed
308 if url:
309 profile = read_profile(url)
310 basis = _verify(profile, ctx) if profile is not None else ""
311 if by_email:
312 _anchor_profile(ctx, url, profile, "deepline")
313 ctx.match_basis.append(EMAIL_LOOKUP_BASIS)
314 if basis:
315 ctx.match_basis += [basis, SELF_REPORTED_BASIS]
316 ctx.set_linkedin_status(person.LINKEDIN_CHECKED if profile is not None else person.LINKEDIN_FAILED)
317 return
318 if basis:
319 _anchor_profile(ctx, url, profile, "deepline")
320 ctx.match_basis += [basis, SELF_REPORTED_BASIS]
321 ctx.set_linkedin_status(person.LINKEDIN_CHECKED)
322 return
323 rejected = rejected or profile is not None
324
325 if rejected:
326 ctx.set_linkedin_status(person.LINKEDIN_REJECTED)
327 elif failed:
328 ctx.set_linkedin_status(person.LINKEDIN_FAILED)
329 else:
330 ctx.set_linkedin_status(person.LINKEDIN_NOT_FOUND)
331
332
333 def resolve_linkedin(
334 ctx: PersonContext,
335 config: dict,
336 *,
337 deadline_monotonic: float | None,
338 run_id: str,
339 requested_sources: Iterable[str] | None = None,
340 ) -> PersonContext:
341 """Resolve, read, and verify the person's LinkedIn profile into ``ctx``.
342
343 Makes at most the Deepline client's per-run paid calls (one lookup, two
344 profile reads). Never raises for a provider failure: it becomes the
345 "failed" status.
346 """
347 anchor_supplied_url(ctx)
348 client = deepline.from_config(config, run_id)
349 try:
350 if ctx.linkedin_url:
351 _read_supplied(ctx, config, client, deadline_monotonic, requested_sources)
352 elif client is None:
353 ctx.set_linkedin_status(person.LINKEDIN_NO_KEY)
354 else:
355 _look_up(ctx, config, client, deadline_monotonic)
356 except Exception as exc: # noqa: BLE001 - resolution never fails the run
357 _log(f"LinkedIn resolution failed: {type(exc).__name__}")
358 ctx.set_linkedin_status(person.LINKEDIN_FAILED)
359 _log(f"LinkedIn: {ctx.linkedin_status}")
360 return ctx
361
361 lines PYTHON