返回 last30days-skill
person.py
根目录 / skills / last30days / scripts / lib / person.py
1 """Person run context: who the run is about and how to tell them apart.
2
3 A person run starts when the host passes ``--employer``, ``--linkedin``, or
4 ``--email`` for a person topic. The context holds the identity anchors that
5 later stages filter on (employer name, employer domain, and the email domain
6 unless it is a personal-mail provider) plus status fields those stages fill
7 in. With none of the flags there is no context and the run is unchanged.
8
9 The email address itself may drive a lookup but is never an anchor, never
10 logged, and never serialized.
11 """
12
13 from __future__ import annotations
14
15 import re
16 from dataclasses import dataclass, field
17 from urllib.parse import unquote, urlsplit
18
19 # Personal-mail providers: an address here says nothing about an employer.
20 FREEMAIL_DOMAINS = frozenset({
21 "gmail.com", "googlemail.com",
22 "msn.com", "icloud.com", "me.com", "mac.com",
23 "proton.me", "pm.me", "protonmail.com", "protonmail.ch",
24 "mail.com", "email.com", "fastmail.com", "fastmail.fm",
25 "ymail.com", "rocketmail.com", "zoho.com", "zohomail.com",
26 "tutanota.com", "tuta.io", "hey.com", "mail.ru", "web.de",
27 "qq.com", "163.com", "126.com", "naver.com",
28 })
29
30 # Providers with per-country domains (yahoo.co.uk, hotmail.fr, gmx.de).
31 FREEMAIL_PROVIDER_LABELS = frozenset({
32 "yahoo", "hotmail", "outlook", "live", "aol", "gmx", "yandex",
33 })
34
35 LINKEDIN_CHECKED = "checked"
36 LINKEDIN_NO_KEY = "no key"
37 LINKEDIN_FAILED = "failed"
38 LINKEDIN_NOT_FOUND = "profile not found"
39 LINKEDIN_REJECTED = "match rejected"
40 LINKEDIN_STATUSES = (
41 LINKEDIN_CHECKED, LINKEDIN_NO_KEY, LINKEDIN_FAILED, LINKEDIN_NOT_FOUND, LINKEDIN_REJECTED,
42 )
43
44 _DOMAIN = re.compile(r"[a-z0-9-]+(\.[a-z0-9-]+)+")
45 _EMAIL = re.compile(r"[^@\s]+@([a-z0-9-]+(?:\.[a-z0-9-]+)+)")
46 _LINKEDIN_SLUG = re.compile(r"[A-Za-z0-9_%-]+")
47
48
49 def is_freemail_domain(domain: str) -> bool:
50 """True when ``domain`` belongs to a personal-mail provider."""
51 domain = (domain or "").strip().lower().rstrip(".")
52 if domain in FREEMAIL_DOMAINS:
53 return True
54 label, _, suffix = domain.partition(".")
55 # yahoo.co.uk or hotmail.com.br, but not outlook-freight.example.
56 return (
57 label in FREEMAIL_PROVIDER_LABELS
58 and bool(suffix)
59 and all(0 < len(part) <= 3 for part in suffix.split("."))
60 )
61
62
63 def _site_domain(site: str) -> str:
64 """A bare lowercase host from a domain or URL, without ``www.``, or ""."""
65 text = (site or "").strip()
66 host = re.sub(r"^[a-z][a-z0-9+.-]*://", "", text, flags=re.IGNORECASE)
67 host = re.split(r"[/?#:]", host, maxsplit=1)[0].strip().lower().rstrip(".")
68 if not _DOMAIN.fullmatch(host):
69 return ""
70 return host[4:] if host.startswith("www.") else host
71
72
73 def parse_employer(raw: str) -> tuple[str, str]:
74 """``"Name[:domain]"`` -> (name, domain). Raises ValueError when malformed.
75
76 The name is everything before the first colon; the domain may be a bare
77 domain or a URL and reduces to its host.
78 """
79 name, colon, site = (raw or "").partition(":")
80 name = " ".join(name.split())[:80]
81 if not name:
82 raise ValueError('--employer needs a company name, as "Name" or "Name:domain"')
83 domain = ""
84 if colon and site.strip():
85 domain = _site_domain(site)
86 if not domain:
87 raise ValueError(
88 f"--employer {name}: the part after the colon is not a domain or URL"
89 )
90 return name, domain
91
92
93 def normalize_linkedin_url(raw: str) -> str:
94 """An http(s) linkedin.com/in/<slug> URL -> https://www.linkedin.com/in/<slug>.
95
96 Raises ValueError for anything else.
97 """
98 error = ValueError(
99 "--linkedin must be a profile URL like https://www.linkedin.com/in/<name>"
100 )
101 text = (raw or "").strip()
102 try:
103 parts = urlsplit(text)
104 except ValueError:
105 raise error from None
106 host = (parts.hostname or "").lower()
107 if parts.scheme.lower() not in {"http", "https"}:
108 raise error
109 if host != "linkedin.com" and not host.endswith(".linkedin.com"):
110 raise error
111 segments = [segment for segment in parts.path.split("/") if segment]
112 if len(segments) < 2 or segments[0].lower() != "in":
113 raise error
114 slug = segments[1]
115 if not _LINKEDIN_SLUG.fullmatch(slug) or not unquote(slug).strip("-_"):
116 raise error
117 return f"https://www.linkedin.com/in/{slug.lower()}"
118
119
120 def _email_domain(raw: str) -> str:
121 """The domain of a plausible email address. Raises ValueError otherwise.
122
123 The message never repeats the address.
124 """
125 match = _EMAIL.fullmatch((raw or "").strip().lower())
126 if not match:
127 raise ValueError("--email is not an email address (expected name@domain)")
128 return match.group(1)
129
130
131 @dataclass
132 class PersonContext:
133 """Identity inputs and resolution state for one person run."""
134
135 full_name: str
136 employer_name: str = ""
137 employer_domain: str = ""
138 # Domain of a work address; "" for a personal-mail address or none.
139 email_domain: str = ""
140 # The full address, for a lookup only. Never logged or serialized.
141 email: str = field(default="", repr=False)
142 linkedin_url: str = ""
143 # Text anchors an item must match to count as this person.
144 anchors: list[str] = field(default_factory=list)
145 # No anchor and no user-supplied profile: identity is uncertain.
146 identity_weak: bool = False
147 linkedin_status: str | None = None
148 match_basis: list[str] = field(default_factory=list)
149 linkedin_mismatch: str = ""
150 profile: dict = field(default_factory=dict)
151 bio: dict = field(default_factory=dict)
152 derived_handles: dict = field(default_factory=dict)
153 older_posts: list[dict] = field(default_factory=list)
154 dropped_counts: dict = field(default_factory=dict)
155 timed_out: bool = False
156 # Posts from the person's own LinkedIn inside the window, and every
157 # first-party item (LinkedIn posts plus the resolved X and GitHub
158 # accounts) inside the window. Older activity shows only when the
159 # second count is thin.
160 in_window_posts: int = 0
161 first_party_in_window: int = 0
162 # True only when the posts read finished; a failed or timed-out read
163 # leaves the post count unknown, not zero.
164 posts_read: bool = False
165
166 def add_anchor(self, anchor: str) -> None:
167 """Add a text anchor once, ignoring case."""
168 anchor = " ".join((anchor or "").split())
169 if anchor and anchor.lower() not in {a.lower() for a in self.anchors}:
170 self.anchors.append(anchor)
171
172 def set_linkedin_status(self, status: str) -> None:
173 if status not in LINKEDIN_STATUSES:
174 raise ValueError(f"unknown LinkedIn status {status!r}")
175 self.linkedin_status = status
176
177 def to_dict(self) -> dict:
178 """JSON-safe view for artifacts. Omits the email address."""
179 return {
180 "full_name": self.full_name,
181 "employer_name": self.employer_name,
182 "employer_domain": self.employer_domain,
183 "email_domain": self.email_domain,
184 "email_given": bool(self.email),
185 "linkedin_url": self.linkedin_url,
186 "anchors": list(self.anchors),
187 "identity_weak": self.identity_weak,
188 "linkedin_status": self.linkedin_status,
189 "match_basis": list(self.match_basis),
190 "linkedin_mismatch": self.linkedin_mismatch,
191 "profile": dict(self.profile),
192 "bio": dict(self.bio),
193 "derived_handles": dict(self.derived_handles),
194 "older_posts": list(self.older_posts),
195 "dropped_counts": dict(self.dropped_counts),
196 "timed_out": self.timed_out,
197 "in_window_posts": self.in_window_posts,
198 "first_party_in_window": self.first_party_in_window,
199 "posts_read": self.posts_read,
200 }
201
202
203 def build_person_context(
204 topic: str,
205 employer: str | None = None,
206 linkedin: str | None = None,
207 email: str | None = None,
208 ) -> PersonContext | None:
209 """The person context for these flags, or None when none was passed.
210
211 Raises ValueError, naming the flag, when a value is malformed.
212 """
213 if employer is None and linkedin is None and email is None:
214 return None
215 ctx = PersonContext(full_name=" ".join((topic or "").split()))
216 if employer is not None:
217 ctx.employer_name, ctx.employer_domain = parse_employer(employer)
218 ctx.add_anchor(ctx.employer_name)
219 ctx.add_anchor(ctx.employer_domain)
220 if linkedin is not None:
221 ctx.linkedin_url = normalize_linkedin_url(linkedin)
222 if email is not None:
223 domain = _email_domain(email)
224 ctx.email = email.strip()
225 if not is_freemail_domain(domain):
226 ctx.email_domain = domain
227 ctx.add_anchor(domain)
228 ctx.identity_weak = not ctx.anchors and not ctx.linkedin_url
229 return ctx
230
231
232 # -- handle discovery ----------------------------------------------------------
233
234 _NON_SITE_HOSTS = (
235 "linkedin.com", "x.com", "twitter.com", "github.com", "facebook.com",
236 "instagram.com", "youtube.com", "tiktok.com", "threads.net", "bsky.app",
237 "medium.com", "substack.com",
238 )
239
240
241 def _compact(text: str) -> str:
242 return re.sub(r"[^a-z0-9]", "", (text or "").lower())
243
244
245 def _company_markers(ctx: PersonContext) -> list[str]:
246 """Compact forms of the employer's name and site labels. A handle or site
247 containing one is the company's account, not the person's."""
248 from . import company_names
249
250 markers = [_compact(company_names.name_key(ctx.employer_name))]
251 for domain in (ctx.employer_domain, ctx.email_domain):
252 if domain:
253 markers.append(_compact(domain.split(".")[0]))
254 return [marker for marker in markers if len(marker) >= 3]
255
256
257 def _is_company(name: str, ctx: PersonContext) -> bool:
258 compact = _compact(name)
259 return any(marker in compact for marker in _company_markers(ctx))
260
261
262 def same_or_subdomain(host: str, domain: str) -> bool:
263 return bool(host and domain) and (host == domain or host.endswith("." + domain))
264
265
266 def discover_handles(ctx: PersonContext) -> dict:
267 """X handle, GitHub user and personal site from the person's own links.
268
269 Links from the person's block on the employer's bio page come before the
270 profile's listed websites. A link whose handle or host names the employer
271 (its name key or its domain) is the company's account and is skipped.
272 Returns only what was found, e.g. ``{"x": ..., "github": ..., "site": ...}``.
273 """
274 from . import resolve
275
276 links = list((ctx.bio or {}).get("links") or []) + list((ctx.profile or {}).get("websites") or [])
277 found: dict = {}
278 for raw in links:
279 url = str(raw or "").strip()
280 if not url.startswith(("http://", "https://")):
281 continue
282 x_match = resolve._X_PROFILE_LINK.match(url)
283 if x_match:
284 handle = x_match.group(1)
285 if "x" not in found and handle.lower() not in resolve._X_NON_ACCOUNTS and not _is_company(handle, ctx):
286 found["x"] = handle
287 continue
288 gh_match = resolve._GITHUB_OWNER_LINK.match(url)
289 if gh_match:
290 user = gh_match.group(1)
291 if "github" not in found and user.lower() not in resolve._GITHUB_NON_OWNERS and not _is_company(user, ctx):
292 found["github"] = user.lower()
293 continue
294 host = _site_domain(url)
295 if (
296 "site" in found
297 or not host
298 or any(same_or_subdomain(host, social) for social in _NON_SITE_HOSTS)
299 or any(same_or_subdomain(host, d) for d in (ctx.employer_domain, ctx.email_domain))
300 or _is_company(host.rsplit(".", 1)[0], ctx)
301 ):
302 continue
303 found["site"] = url
304 return found
305
306
307 def apply_derived_handles(
308 ctx: PersonContext, *, x_handle: str | None, github_user: str | None,
309 ) -> tuple[str | None, str | None]:
310 """Fill empty handle slots from the person's own links.
311
312 Host-passed handles always win. What fills a slot (and any personal site)
313 is recorded in ``ctx.derived_handles``, which marks it as discovered by
314 the engine rather than supplied. Returns the (x_handle, github_user) to use.
315 """
316 found = discover_handles(ctx)
317 derived: dict = {}
318 if not x_handle and found.get("x"):
319 x_handle = derived["x"] = found["x"]
320 if not github_user and found.get("github"):
321 github_user = derived["github"] = found["github"]
322 if found.get("site"):
323 derived["site"] = found["site"]
324 ctx.derived_handles = derived
325 return x_handle, github_user
326
326 lines PYTHON