返回 last30days-skill
company_resolve.py
根目录 / skills / last30days / scripts / lib / company_resolve.py
1 """Resolve a research topic to the company it names, through Wikidata.
2
3 One conservative lookup, keyless. A wrong company or a wrong ticker is far
4 worse than none, so every step that is not certain returns nothing. When
5 Wikidata names nothing and ``EXA_API_KEY`` is in the caller's config, an
6 undated Exa official-site search is the only extra step: it can fill
7 ``company`` and ``company_site``, never a ticker.
8
9 - The company is certain when Wikidata's top search hit for the topic carries
10 the topic as its label or an alias and is a business, or is a person who is
11 the current chief executive of exactly one organization, itself a business.
12 There is no hop from a product to its maker or from a subsidiary to its
13 parent.
14 - The one hop is downward, from a company that is already certain to the names
15 its own Wikidata record lists, and it is made only for a caller that asks
16 for them (``names=True``). A holding company files little under its own
17 name, so a caller searching filings needs these, and it treats each one as a
18 name that certainly belongs to the company. So only names that could be a
19 legal filing name and that say something new are returned, compared by the
20 key filings are matched by (case, punctuation and trailing legal designators
21 removed):
22
23 - Own names, at most ``MAX_OWN_NAMES``: the English official names, current
24 ones first, then the English and all-language label and aliases. One is
25 kept when its key has at least two words, it ends in a legal designator
26 (a nickname such as "Big Blue" does not), it is not a domain, it carries
27 no parenthetical, and its key is not the company's own or one already
28 kept. "Microsoft Corp." adds nothing to "Microsoft"; "MS" and
29 "microsoft.com" could be anyone.
30 - Subsidiary names, at most ``MAX_SUBSIDIARY_NAMES``: the labels of the
31 current subsidiaries, then of what the company owns, in the record's
32 order. One is kept when its key has at least three characters, is not
33 already kept, and does not extend the company's own name ("Microsoft
34 Algeria" is already reachable from "Microsoft").
35
36 The names are not checked to be companies, and a long list of subsidiaries
37 is not returned whole.
38 - The ticker is certain when the company has exactly one primary listing:
39 the one listing marked preferred, or the only listing when none is marked.
40 A listing with an end time is ignored. Two share classes or two exchanges
41 with none marked give no ticker. They give ``ticker_candidates`` instead:
42 the symbols of the current listings, for a caller that can confirm one of
43 them against a second source. A candidate is never a ticker on its own.
44
45 Any error, timeout or unexpected response returns nothing and logs once. That
46 nothing is a ``FailedLookup``, so a caller can tell "Wikidata did not answer"
47 from "Wikidata answered and nothing is certain". The one exception is the
48 one request for the subsidiaries' labels, made only when the names are asked
49 for: the company is certain before it is made, so its failure logs once and
50 costs only the subsidiary names.
51 """
52
53 from __future__ import annotations
54
55 import re
56 from typing import Any
57 from urllib.parse import urlsplit
58
59 from . import grounding, http, log, public_host
60 from .company_names import name_key
61
62 WIKIDATA_API = "https://www.wikidata.org/w/api.php"
63 TIMEOUT_SECONDS = 5
64
65 _INSTANCE_OF = "P31"
66 _SUBCLASS_OF = "P279"
67 _STOCK_EXCHANGE = "P414"
68 _TICKER_SYMBOL = "P249"
69 _CHIEF_EXECUTIVE = "P169"
70 _OFFICIAL_WEBSITE = "P856"
71 _END_TIME = "P582"
72 _OFFICIAL_NAME = "P1448"
73 _SUBSIDIARY = "P355"
74 _OWNER_OF = "P1830"
75
76 MAX_OWN_NAMES = 3
77 MAX_SUBSIDIARY_NAMES = 12
78 MAX_COMPANY_NAMES = MAX_OWN_NAMES + MAX_SUBSIDIARY_NAMES
79 # Labels are asked for more subsidiaries than are kept, so one that is
80 # filtered out does not cost a later one its place. One request takes 50 ids.
81 _MAX_LABEL_IDS = 50
82 _DOMAIN = re.compile(r"(?:[\w-]+\.)+[a-z]{2,}", re.IGNORECASE)
83
84 _HUMAN = "Q5"
85 # business, enterprise, company, public company, corporation. "organization"
86 # is left out on purpose: bands, parties and constituencies sit under it.
87 _BUSINESS_CLASSES = frozenset({"Q4830453", "Q6881511", "Q783794", "Q891723", "Q167037"})
88 # Direct P31 only: a product company named after its app is often
89 # "software" / "application" and must still get company peers.
90 _LANGUAGE_OR_OS_CLASSES = frozenset({
91 "Q9143", # programming language
92 "Q9135", # operating system
93 })
94 # A person recorded as chief executive of more organizations than this is not
95 # checked further; the answer would be "more than one" or a very large fetch.
96 _MAX_LED_ORGANIZATIONS = 5
97
98 _GENERIC_TOPIC_WORDS = frozenset({
99 "how", "what", "why", "best", "top", "tutorial", "guide", "prompts",
100 "news", "latest", "ideas", "examples",
101 })
102 _KNOWN_SINGLE_WORD_COMPANIES = frozenset({
103 "apple", "uber", "google", "microsoft", "amazon", "meta", "netflix",
104 "openai", "anthropic", "qualtrics", "stripe", "brex",
105 })
106 _COMMON_TECH_TERMS = frozenset({
107 "python", "ruby", "javascript", "typescript", "java", "go", "golang",
108 "rust", "php", "swift", "kotlin", "scala", "clojure", "elixir",
109 "react", "vue", "angular", "svelte", "node", "django", "rails",
110 "postgres", "mysql", "redis", "kubernetes", "docker",
111 })
112
113 # Directories, news, and social profiles that Exa often ranks near a named
114 # company's own site. A hit on one of these is not an official homepage.
115 _EXA_DIRECTORY_HOSTS = frozenset({
116 "wikipedia.org", "crunchbase.com", "linkedin.com", "bloomberg.com",
117 "pitchbook.com", "facebook.com", "twitter.com", "x.com", "youtube.com",
118 "instagram.com", "tiktok.com", "reddit.com", "glassdoor.com", "indeed.com",
119 "owler.com", "zoominfo.com", "cbinsights.com", "similarweb.com",
120 "google.com", "bing.com", "yahoo.com", "tracxn.com", "craft.co",
121 })
122 _EXA_HOMEPAGE_PATHS = frozenset({"", "/en", "/en-us", "/home"})
123 EXA_COMPANY_SOURCE = "exa"
124 # Trailing generic words dropped once when the compact topic is not the
125 # registrable label ("Modal Labs" → modal.com). Not prefixes, and not "co"
126 # (that would let StripeCo claim stripe.com).
127 _TRAILING_LABEL_WORDS = frozenset({
128 "labs", "lab", "ai", "hq", "inc", "technologies", "systems",
129 "studio", "studios",
130 })
131 COMPANY_PEER_KEYWORD = "keyword"
132 WIKIDATA_NONE = "none"
133 WIKIDATA_HUMAN = "human"
134 WIKIDATA_SOFTWARE = "software"
135
136
137 class FailedLookup(dict):
138 """The empty result of a lookup that failed, as opposed to one Wikidata
139 answered. It is an empty dict to every caller that does not ask."""
140
141
142 class UncertainLookup(dict):
143 """Wikidata answered and nothing is certain.
144
145 Empty to every caller that does not ask. ``kind`` is ``none`` (no matching
146 entity, or a non-business that is not a language or OS), ``human``, or
147 ``software`` (a programming language or operating system, direct P31).
148 """
149
150 def __init__(self, kind: str = WIKIDATA_NONE):
151 super().__init__()
152 self.kind = kind
153
154
155 def company_topic_likely(topic: str) -> bool:
156 """Whether a topic is shaped like a company or a person's name.
157
158 A cheap shape check, with no network: questions, long topics and generic
159 research phrasing are not company topics.
160 """
161 text = topic.strip()
162 if not text:
163 return False
164 lower = text.lower()
165 if "?" in text or len(text.split()) > 4:
166 return False
167 if any(word in _GENERIC_TOPIC_WORDS for word in lower.split()):
168 return False
169 if " vs " in lower or " versus " in lower:
170 parts = re.split(r"\s+(?:vs|versus)\s+", text, maxsplit=1, flags=re.IGNORECASE)
171 if len(parts) != 2:
172 return False
173 return _comparison_side_company_like(parts[0]) or _comparison_side_company_like(parts[1])
174 return bool(text[:1].isupper() or lower in _KNOWN_SINGLE_WORD_COMPANIES)
175
176
177 def _comparison_side_company_like(side: str) -> bool:
178 token = re.sub(r"[^\w.+#-]", "", side.strip().split()[0] if side.strip() else "")
179 if not token:
180 return False
181 lower = token.lower()
182 if lower in _COMMON_TECH_TERMS:
183 return False
184 return bool(token[:1].isupper() or lower in _KNOWN_SINGLE_WORD_COMPANIES)
185
186
187 def resolve_company(
188 topic: str, *, listing: bool = True, names: bool = False,
189 config: dict | None = None,
190 ) -> dict[str, Any]:
191 """Return what is certain about the company a topic names.
192
193 Keys, each present only when resolved: ``company``, ``company_site``,
194 ``ticker``, ``exchange``, ``ticker_candidates`` (the current listings'
195 symbols, only when the company is certain and its ticker is not),
196 ``company_names`` (only with ``names``; other names that certainly belong
197 to the company: its official names and aliases that could be a legal
198 filing name, then its subsidiaries, at most ``MAX_COMPANY_NAMES`` distinct
199 strings and never ``company`` itself), and
200 ``company_via_person`` (True) when the topic is the person who leads
201 the company. ``company_peer_discovery`` is ``keyword`` when Wikidata's
202 top hit is a human with no unique company, or directly a programming
203 language or operating system, so competitor discovery keeps keyword
204 SERPs. A food, occupation, application, or other homonym is treated
205 like no entity: Exa may still fill the site and company peers stay on.
206 An empty dict means nothing is certain; it
207 is a ``FailedLookup`` when the lookup itself failed, and an
208 ``UncertainLookup`` when Wikidata answered with nothing certain and Exa
209 did not fill a site. No request is made for a topic that is not
210 company-shaped. With ``listing`` off the company's stock listing is not
211 read, so there is no ``ticker``, ``exchange`` or ``ticker_candidates``.
212 Without ``names`` the company's other names are not read: there is no
213 ``company_names`` and no request for the subsidiaries' labels. Only a
214 caller that searches filings under those names needs them.
215
216 ``config`` is optional. When Wikidata answers with nothing certain and
217 ``EXA_API_KEY`` is set, an undated official-site search can fill
218 ``company`` and ``company_site`` (``company_source`` is ``exa``). A
219 failed Wikidata lookup is not retried on Exa, so the Yahoo ticker
220 backup still runs.
221 """
222 if not company_topic_likely(topic):
223 return {}
224 try:
225 found = _resolve(" ".join(topic.split()), listing, names)
226 except Exception as exc:
227 log.source_log(
228 "Company",
229 f"Wikidata lookup failed for {topic!r}: {type(exc).__name__}: {exc}",
230 tty_only=False,
231 )
232 return FailedLookup()
233 if found:
234 return found
235 kind = found.kind if isinstance(found, UncertainLookup) else WIKIDATA_NONE
236 filled = _exa_site_fallback(topic, config, wikidata_kind=kind)
237 return filled or found
238
239
240 def _is_directory_host(host: str) -> bool:
241 return any(host == domain or host.endswith("." + domain) for domain in _EXA_DIRECTORY_HOSTS)
242
243
244 def _compact_name(text: str) -> str:
245 return re.sub(r"[^a-z0-9]", "", text.casefold())
246
247
248 def _registrable_label(host: str) -> str:
249 """The registered-domain name (eTLD+1), same split as resolve.py.
250
251 ``stripe.com`` → ``stripe``; ``foo.co.uk`` → ``foo``;
252 ``stripeco.example.org`` → ``example``. Two-label ccSLDs in the last
253 two labels are ``co`` / ``com`` under a 2-letter ccTLD only; that is
254 the repo's existing conservative heuristic, not a public-suffix list.
255 """
256 labels = [part for part in host.split(".") if part]
257 if len(labels) < 2:
258 return ""
259 name = (
260 labels[-3]
261 if labels[-2] in {"co", "com"} and len(labels[-1]) == 2 and len(labels) >= 3
262 else labels[-2]
263 )
264 return _compact_name(name)
265
266
267 def _compact_topic_keys(topic: str) -> tuple[str, ...]:
268 """Registrable-label keys for this topic: the compact name, then one trim.
269
270 After the full compact name fails, one trailing generic word (labs, ai,
271 hq, ...) may be dropped from the topic. The domain is never trimmed, and
272 a shared prefix is never a match.
273 """
274 keys: list[str] = []
275 seen: set[str] = set()
276
277 def add(text: str) -> None:
278 key = _compact_name(name_key(text)) or _compact_name(text)
279 if key and key not in seen:
280 seen.add(key)
281 keys.append(key)
282
283 add(topic)
284 words = topic.split()
285 if len(words) >= 2:
286 last = re.sub(r"[^a-z0-9]+", "", words[-1].casefold())
287 if last in _TRAILING_LABEL_WORDS:
288 add(" ".join(words[:-1]))
289 return tuple(keys)
290
291
292 def _exa_hit_site(url: str) -> tuple[str, str, str] | None:
293 """Registrable label, homepage (or ''), and host root, or None if unusable."""
294 host = _site_host(url)
295 if not host or _is_directory_host(host):
296 return None
297 label = _registrable_label(host)
298 if not label:
299 return None
300 return label, _exa_homepage(url), f"https://{host}/"
301
302
303 def _exa_site_matches_topic(topic: str, url: str) -> bool:
304 """True when the URL's registrable label is this company, not a look-alike.
305
306 The compact topic (legal designators stripped via ``name_key``) must
307 equal the registrable label. If that misses, one trailing generic word
308 may be dropped from the topic (``Modal Labs`` → ``modal.com``). Shared
309 prefixes (``StripeCo`` / ``stripe.com``) and a matching first label on
310 someone else's domain (``stripeco.example.org``) do not count.
311 """
312 hit = _exa_hit_site(url)
313 return bool(hit) and hit[0] in _compact_topic_keys(topic)
314
315
316 def _exa_homepage(url: str) -> str:
317 """The site root when the path is a homepage, else ''."""
318 host = _site_host(url)
319 if not host:
320 return ""
321 parsed = urlsplit(str(url).strip())
322 path = (parsed.path or "").rstrip("/").lower()
323 if path not in _EXA_HOMEPAGE_PATHS:
324 return ""
325 return f"https://{host}/"
326
327
328 def _pick_exa_official_site(topic: str, items: list[dict]) -> str:
329 """The Exa hit that looks like this company's own homepage.
330
331 An exact registrable-label match against the full compact topic
332 (``Acme Labs`` → ``acmelabs.com``) wins over a match that needed a
333 trailing generic word trimmed (``acme.com``), regardless of result
334 order. Homepages beat a host-root fallback within each of those
335 tiers.
336 """
337 keys = _compact_topic_keys(topic)
338 if not keys:
339 return ""
340 exact, *rest = keys
341 trimmed = rest[0] if rest else ""
342
343 def first_site(want: str) -> str:
344 fallback = ""
345 for item in items:
346 hit = _exa_hit_site(str(item.get("url") or ""))
347 if not hit or hit[0] != want:
348 continue
349 homepage, host_root = hit[1], hit[2]
350 if homepage:
351 return homepage
352 if not fallback:
353 fallback = host_root
354 return fallback
355
356 return first_site(exact) or (first_site(trimmed) if trimmed else "")
357
358
359 def _exa_site_fallback(
360 topic: str, config: dict | None, *, wikidata_kind: str = WIKIDATA_NONE,
361 ) -> dict[str, Any]:
362 """Official-site search when Wikidata named nothing certain.
363
364 Searches Exa's company index only (undated). A person, language, or OS
365 site is kept; ``wikidata_kind`` decides whether peer discovery may use
366 that company index (``none``) or must stay on keyword SERPs (``human``,
367 ``software``).
368 """
369 api_key = grounding.exa_api_key(config)
370 if not api_key:
371 return {}
372 try:
373 items, _artifact = grounding.exa_company_search(
374 f"official website of {topic}; exclude similarly named firms",
375 api_key,
376 count=5,
377 objective=(
378 f"Find the official homepage of {topic}. Rank that company's own "
379 "site first. Exclude similarly named firms, directories, news "
380 "articles, and social profiles."
381 ),
382 )
383 except Exception as exc:
384 log.source_log(
385 "Company",
386 f"Exa official-site lookup failed for {topic!r}: "
387 f"{type(exc).__name__}: {exc}",
388 tty_only=False,
389 )
390 return {}
391 site = _pick_exa_official_site(topic, items)
392 if not site:
393 return {}
394 log.source_log(
395 "Company",
396 f"Exa official site for {topic!r}: {site}",
397 tty_only=False,
398 )
399 found: dict[str, Any] = {
400 "company": topic, "company_site": site, "company_source": EXA_COMPANY_SOURCE,
401 }
402 if wikidata_kind in {WIKIDATA_HUMAN, WIKIDATA_SOFTWARE}:
403 found["company_peer_discovery"] = COMPANY_PEER_KEYWORD
404 return found
405
406
407 def _resolve(topic: str, listing: bool = True, names: bool = False) -> dict[str, Any]:
408 hits = _api({
409 "action": "wbsearchentities", "search": topic, "language": "en",
410 "uselang": "en", "type": "item", "limit": 1,
411 })["search"]
412 if not hits:
413 return UncertainLookup(WIKIDATA_NONE)
414 top_id = hits[0]["id"]
415 entity = _entities([top_id], "labels|aliases|claims")[top_id]
416 if topic.casefold() not in _names(entity):
417 return UncertainLookup(WIKIDATA_NONE)
418 if _HUMAN in _item_ids(_statements(entity, _INSTANCE_OF)):
419 company = _company_led_by(top_id)
420 if company is None:
421 return UncertainLookup(WIKIDATA_HUMAN)
422 return {**_company_fields(company, listing, names), "company_via_person": True}
423 if _is_language_or_os(entity):
424 return UncertainLookup(WIKIDATA_SOFTWARE)
425 if _is_business(entity):
426 return _company_fields(entity, listing, names)
427 return UncertainLookup(WIKIDATA_NONE)
428
429
430 # Wikimedia's User-Agent policy asks for a contact URL. Without one, Wikidata
431 # answers bursts with 429: two company runs at once lost their resolution.
432 WIKIMEDIA_USER_AGENT = "last30days-skill (https://github.com/mvanhorn/last30days-skill)"
433
434
435 def _api(params: dict[str, Any]) -> dict[str, Any]:
436 data = http.get(
437 WIKIDATA_API,
438 headers={"User-Agent": WIKIMEDIA_USER_AGENT},
439 params={**params, "format": "json"},
440 timeout=TIMEOUT_SECONDS,
441 retries=1,
442 )
443 if not isinstance(data, dict) or "error" in data:
444 raise ValueError(f"unexpected Wikidata response for {params.get('action')}")
445 return data
446
447
448 def _entities(ids: list[str], props: str) -> dict[str, dict[str, Any]]:
449 found = _api({
450 "action": "wbgetentities", "ids": "|".join(ids), "props": props,
451 "languages": "en|mul",
452 })["entities"]
453 for entity_id in ids:
454 if "missing" in found[entity_id]:
455 raise ValueError(f"Wikidata has no entity {entity_id}")
456 return found
457
458
459 def _names(entity: dict[str, Any]) -> set[str]:
460 """English and all-language labels and aliases, case-folded."""
461 names = {label["value"] for label in entity.get("labels", {}).values()}
462 for aliases in entity.get("aliases", {}).values():
463 names.update(alias["value"] for alias in aliases)
464 return {" ".join(name.split()).casefold() for name in names}
465
466
467 def _statements(entity: dict[str, Any], prop: str) -> list[dict[str, Any]]:
468 """Statements that hold a value and are not deprecated."""
469 return [
470 statement
471 for statement in entity.get("claims", {}).get(prop, [])
472 if statement["rank"] != "deprecated" and statement["mainsnak"]["snaktype"] == "value"
473 ]
474
475
476 def _preferred_or_all(statements: list[dict[str, Any]]) -> list[dict[str, Any]]:
477 preferred = [statement for statement in statements if statement["rank"] == "preferred"]
478 return preferred or statements
479
480
481 def _value(statement: dict[str, Any]) -> Any:
482 return statement["mainsnak"]["datavalue"]["value"]
483
484
485 def _item_ids(statements: list[dict[str, Any]]) -> set[str]:
486 return {_value(statement)["id"] for statement in statements}
487
488
489 def _ended(statement: dict[str, Any]) -> bool:
490 return _END_TIME in statement.get("qualifiers", {})
491
492
493 def _is_instance_of(entity: dict[str, Any], class_ids: frozenset[str]) -> bool:
494 """True when the entity is an instance of one of ``class_ids``, or of a
495 class that is itself a direct subclass of one (same P279 hop as business)."""
496 classes = _item_ids(_statements(entity, _INSTANCE_OF))
497 if classes & class_ids:
498 return True
499 if not classes:
500 return False
501 parents = _entities(sorted(classes), "claims")
502 return any(
503 _item_ids(_statements(parent, _SUBCLASS_OF)) & class_ids
504 for parent in parents.values()
505 )
506
507
508 def _is_business(entity: dict[str, Any]) -> bool:
509 """True when the entity is an instance of a business class, or of a class
510 that is itself a direct subclass of one (an automobile manufacturer)."""
511 return _is_instance_of(entity, _BUSINESS_CLASSES)
512
513
514 def _is_language_or_os(entity: dict[str, Any]) -> bool:
515 """True when P31 is a programming language or OS. No P279 hop."""
516 return bool(_item_ids(_statements(entity, _INSTANCE_OF)) & _LANGUAGE_OR_OS_CLASSES)
517
518
519 def _company_led_by(person_id: str) -> dict[str, Any] | None:
520 """The one business whose current chief executive is this person."""
521 found = _api({
522 "action": "query", "list": "search", "srprop": "",
523 "srsearch": f"haswbstatement:{_CHIEF_EXECUTIVE}={person_id}",
524 "srlimit": _MAX_LED_ORGANIZATIONS + 1,
525 })["query"]
526 ids = [hit["title"] for hit in found["search"]]
527 if not ids or len(ids) > _MAX_LED_ORGANIZATIONS or found["searchinfo"]["totalhits"] > len(ids):
528 return None
529 organizations = _entities(ids, "labels|aliases|claims")
530 led = [
531 organization
532 for organization in organizations.values()
533 if any(
534 _value(statement)["id"] == person_id and not _ended(statement)
535 for statement in _preferred_or_all(_statements(organization, _CHIEF_EXECUTIVE))
536 )
537 ]
538 if len(led) != 1 or not _is_business(led[0]):
539 return None
540 return led[0]
541
542
543 _RESERVED_HOST_SUFFIXES = frozenset({"localhost", "local", "internal", "localdomain", "arpa"})
544 _VALID_HOST_RE = re.compile(
545 r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+"
546 )
547 _VALID_TLD_RE = re.compile(r"[a-z]{2,63}|xn--[a-z0-9-]{2,59}")
548
549
550 def _site_host(url: str) -> str:
551 raw = str(url).strip() if url is not None else ""
552 if not raw or "\\" in raw or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in raw):
553 return ""
554 try:
555 parsed = urlsplit(raw)
556 port = parsed.port
557 except ValueError:
558 return ""
559 scheme = parsed.scheme.lower()
560 if scheme not in {"http", "https"}:
561 return ""
562 if parsed.username is not None or parsed.password is not None:
563 return ""
564 if not parsed.netloc.isascii() or "%" in parsed.netloc:
565 return ""
566 if port is not None and not (
567 (scheme == "https" and port == 443) or (scheme == "http" and port == 80)
568 ):
569 return ""
570 host = (parsed.hostname or "").lower().rstrip(".")
571 if not host or not _VALID_HOST_RE.fullmatch(host):
572 return ""
573 if public_host._parse_ip_literal(host) is not None:
574 return ""
575 labels = host.split(".")
576 if host == "localhost" or labels[-1] in _RESERVED_HOST_SUFFIXES:
577 return ""
578 if not _VALID_TLD_RE.fullmatch(labels[-1]):
579 return ""
580 bare = host.removeprefix("www.")
581 if "." not in bare:
582 return ""
583 return bare
584
585
586 def _official_site(sites: list[dict[str, Any]]) -> str:
587 """The one official site, or "" when the statements do not settle one.
588
589 A single statement is the site. Several with no preferred one settle a
590 site only when most of them are on one host, as with a company that lists
591 a regional page per country (apple.com/de/, apple.com/jp/, ...): the site
592 is that host's root.
593 """
594 if len(sites) == 1:
595 raw = _value(sites[0])
596 if not isinstance(raw, str):
597 return ""
598 candidate = raw.strip()
599 if not _site_host(candidate) or not public_host.is_public_address_syntax(candidate):
600 return ""
601 return candidate
602 hosts = [_site_host(_value(site)) for site in sites]
603 if not hosts:
604 return ""
605 top = max(set(hosts), key=hosts.count)
606 if not top or hosts.count(top) * 2 <= len(hosts):
607 return ""
608 return f"https://{top}/"
609
610
611 def _company_fields(
612 entity: dict[str, Any], listing: bool = True, names: bool = False,
613 ) -> dict[str, Any]:
614 labels = entity["labels"]
615 fields: dict[str, Any] = {"company": (labels.get("en") or labels["mul"])["value"]}
616 site = _official_site(_preferred_or_all(_statements(entity, _OFFICIAL_WEBSITE)))
617 if site:
618 fields["company_site"] = site
619 if listing:
620 fields.update(_primary_listing(entity))
621 if names:
622 other_names = _company_names(entity, fields["company"])
623 if other_names:
624 fields["company_names"] = other_names
625 return fields
626
627
628 def _own_names(entity: dict[str, Any]) -> list[str]:
629 """Official names in English, current ones first, then the English and
630 all-language label and aliases."""
631 official = [
632 statement
633 for statement in _statements(entity, _OFFICIAL_NAME)
634 if _value(statement)["language"].split("-")[0] in ("en", "mul")
635 ]
636 official.sort(key=_ended)
637 names = [_value(statement)["text"] for statement in official]
638 labels, aliases = entity.get("labels", {}), entity.get("aliases", {})
639 names.extend(labels[language]["value"] for language in ("en", "mul") if language in labels)
640 names.extend(
641 alias["value"] for language in ("en", "mul") for alias in aliases.get(language, [])
642 )
643 return names
644
645
646 def _subsidiary_ids(entity: dict[str, Any]) -> list[str]:
647 """Current subsidiaries, then what the company owns, in the record's order."""
648 ids = [
649 _value(statement)["id"]
650 for prop in (_SUBSIDIARY, _OWNER_OF)
651 for statement in _statements(entity, prop)
652 if not _ended(statement)
653 ]
654 return list(dict.fromkeys(ids))
655
656
657 def _subsidiary_names(entity: dict[str, Any]) -> list[str]:
658 """Labels of the subsidiaries the company lists, from one request. A
659 failure here is logged and gives none: the company is already certain."""
660 ids = _subsidiary_ids(entity)[:_MAX_LABEL_IDS]
661 if not ids:
662 return []
663 try:
664 found = _entities(ids, "labels")
665 labels = [found[entity_id].get("labels", {}) for entity_id in ids]
666 return [
667 (label.get("en") or label["mul"])["value"]
668 for label in labels
669 if "en" in label or "mul" in label
670 ]
671 except Exception as exc:
672 log.source_log(
673 "Company",
674 f"Wikidata subsidiary names failed for {entity.get('id')}: "
675 f"{type(exc).__name__}: {exc}",
676 tty_only=False,
677 )
678 return []
679
680
681 def _carries_designator(name: str, key: str) -> bool:
682 """True when the name ends in a legal designator ("... Corporation"), which
683 a nickname ("Big Blue") never does: the key is the name without one."""
684 plain = " ".join(re.sub(r"[^\w\s]", " ", name).casefold().split())
685 return plain != key
686
687
688 def _company_names(entity: dict[str, Any], company: str) -> list[str]:
689 """Own names that could be a legal filing name, then subsidiary names,
690 each new under the key filings are matched by."""
691 company_key = name_key(company)
692 seen = {company_key}
693 own: list[str] = []
694 for name in _own_names(entity):
695 name = " ".join(name.split())
696 key = name_key(name)
697 if len(own) == MAX_OWN_NAMES:
698 break
699 if key in seen or " " not in key or "(" in name or _DOMAIN.fullmatch(name):
700 continue
701 if not _carries_designator(name, key):
702 continue
703 seen.add(key)
704 own.append(name)
705 subsidiaries: list[str] = []
706 for name in _subsidiary_names(entity):
707 name = " ".join(name.split())
708 key = name_key(name)
709 if len(subsidiaries) == MAX_SUBSIDIARY_NAMES:
710 break
711 if key in seen or len(key) < 3 or key.startswith(company_key + " "):
712 continue
713 seen.add(key)
714 subsidiaries.append(name)
715 return own + subsidiaries
716
717
718 def _listing_tickers(statement: dict[str, Any]) -> list[str]:
719 return [
720 snak["datavalue"]["value"]
721 for snak in statement.get("qualifiers", {}).get(_TICKER_SYMBOL, [])
722 if snak["snaktype"] == "value"
723 ]
724
725
726 def _primary_listing(entity: dict[str, Any]) -> dict[str, Any]:
727 current = [
728 statement for statement in _statements(entity, _STOCK_EXCHANGE) if not _ended(statement)
729 ]
730 primary = _preferred_or_all(current)
731 tickers = _listing_tickers(primary[0]) if len(primary) == 1 else []
732 if len(tickers) != 1:
733 candidates = list(dict.fromkeys(
734 ticker for statement in current for ticker in _listing_tickers(statement)
735 ))
736 return {"ticker_candidates": candidates} if candidates else {}
737 exchange_id = _value(primary[0])["id"]
738 labels = _entities([exchange_id], "labels")[exchange_id]["labels"]
739 listing = {"ticker": tickers[0]}
740 label = labels.get("en") or labels.get("mul")
741 if label:
742 listing["exchange"] = label["value"]
743 return listing
744
744 lines PYTHON