返回 last30days-skill
competitors.py
根目录 / skills / last30days / scripts / lib / competitors.py
1 """Discover peer entities ("competitors") for a topic via web search.
2
3 Mirrors the `resolve.auto_resolve()` pattern: fan out 2-3 web searches via
4 `grounding.web_search()`, then extract capitalized entity candidates from
5 titles and snippets with deterministic text mining. No LLM call — the
6 hosting reasoning model can always override discovery via
7 `--competitors-list`.
8
9 Returned list is ordered by score (frequency across queries) and capped to
10 the caller's requested count.
11 """
12
13 from __future__ import annotations
14
15 import re
16 from collections import Counter
17 from concurrent.futures import ThreadPoolExecutor, as_completed
18
19 from . import company_resolve, dates, grounding, log
20 from .resolve import _has_backend
21
22 # Peer cap vs total vs-entity cap (main + peers).
23 COMPETITORS_MIN = 1
24 COMPETITORS_MAX = 6
25 COMPETITORS_DEFAULT = 2
26 COMPARISON_ENTITY_MAX = COMPETITORS_MAX + 1
27 # Discovery SERP fan-out is small (3 queries today) but still needs a ceiling
28 # so a future query expansion cannot open one worker per query unbounded.
29 MAX_DISCOVERY_WORKERS = 3
30
31 # A "brand-shaped" token starts with uppercase OR is camelCase with an
32 # uppercase letter later. Catches "Anthropic", "OpenAI", "xAI", "iPhone",
33 # "eBay", "Hugging", "Face".
34 _BRAND_TOKEN = (
35 r"(?:[A-Z][A-Za-z0-9&.\-]*"
36 r"|[a-z][A-Za-z0-9&.\-]*[A-Z][A-Za-z0-9&.\-]*)"
37 )
38
39 # A capitalized phrase of 1-4 brand tokens separated by whitespace.
40 _CAPITALIZED_PHRASE = re.compile(
41 rf"\b{_BRAND_TOKEN}(?:\s+{_BRAND_TOKEN}){{0,3}}\b"
42 )
43
44 # Title-case fillers common in listicle SERPs. Kept flat — extraction
45 # rejects a candidate whose entire tokens are stopwords, not candidates
46 # that merely contain one.
47 _STOPWORD_TOKENS: frozenset[str] = frozenset(
48 token.lower()
49 for token in (
50 # Listicle fillers
51 "Top", "Best", "Worst", "Popular", "Leading", "Similar",
52 "Alternatives", "Alternative", "Competitor", "Competitors",
53 "vs", "Vs", "Versus", "Review", "Reviews", "Comparison",
54 "Guide", "List", "Lists", "Full", "Complete", "Free", "Paid",
55 "Tools", "Tool", "Options", "Rivals", "Rival", "Similar",
56 "Pick", "Picks", "Ranking", "Ranked", "Recommended",
57 # Grammar / time
58 "The", "A", "An", "Of", "In", "For", "To", "With", "On", "At",
59 "By", "From", "Is", "Are", "And", "Or", "But", "Than", "As",
60 "This", "That", "These", "Those", "Our", "Your", "Their",
61 "January", "February", "March", "April", "May", "June", "July",
62 "August", "September", "October", "November", "December",
63 # Years likely to appear as standalone tokens
64 *(str(year) for year in range(2018, 2031)),
65 # Miscellaneous SERP noise
66 "AI", "Apps", "App", "Software", "Platform", "Service", "Startups",
67 "Companies", "Company", "Products", "Product", "Brands", "Brand",
68 )
69 )
70
71
72 def _log(msg: str) -> None:
73 log.source_log("Competitors", msg, tty_only=False)
74
75
76 _BRAND_SUFFIX_TOKENS: frozenset[str] = frozenset({
77 "com", "org", "net", "io", "co", "ai", "dev", "js", "ts", "py",
78 "app", "so", "gg", "sh", "tv", "me", "us", "uk", "de", "fr",
79 "inc", "llc", "ltd", "corp",
80 })
81
82
83 def _brand_tokens(text: str) -> list[str]:
84 """Extract lowercase brand-preserving tokens, trimming stray edge punctuation."""
85 return [
86 cleaned
87 for raw in re.findall(r"[A-Za-z0-9&.\-]+", text.lower())
88 if (cleaned := raw.strip(".-&"))
89 ]
90
91
92 def _identity_token_set(tokens: list[str]) -> set[str]:
93 """Expand brand tokens into comparable self-identity keys without leaking
94 generic suffixes (.com/.js/.io/.dev/.ai) or single-letter fragments."""
95 keys: set[str] = set()
96 for tok in tokens:
97 keys.add(tok)
98 if any(ch in tok for ch in "&.-"):
99 joined = re.sub(r"[^a-z0-9]", "", tok)
100 if len(joined) >= 2:
101 keys.add(joined)
102 if "." in tok:
103 base, suffix = tok.rsplit(".", 1)
104 if suffix in _BRAND_SUFFIX_TOKENS and len(base) >= 2 and base not in _STOPWORD_TOKENS:
105 keys.add(base)
106 max_span = min(len(tokens), 4)
107 for span in range(2, max_span + 1):
108 for start in range(len(tokens) - span + 1):
109 joined_slice = re.sub(r"[^a-z0-9]", "", "".join(tokens[start : start + span]))
110 if len(joined_slice) >= 2:
111 keys.add(joined_slice)
112 if len(tokens) > max_span:
113 whole_joined = re.sub(r"[^a-z0-9]", "", "".join(tokens))
114 if len(whole_joined) >= 2:
115 keys.add(whole_joined)
116 return keys
117
118
119 def _topic_tokens(topic: str) -> set[str]:
120 """Return comparable lowercase identity tokens of the topic, excluding
121 stopwords unless every topic token is a stopword."""
122 tokens = _brand_tokens(topic)
123 if not tokens:
124 return set()
125 all_keys = _identity_token_set(tokens)
126 filtered = {tok for tok in all_keys if tok not in _STOPWORD_TOKENS}
127 return filtered or all_keys
128
129
130 def _candidate_ok(candidate: str, topic_tokens: set[str]) -> bool:
131 """Filter a candidate phrase against stopwords and topic overlap."""
132 tokens = _brand_tokens(candidate)
133 if not tokens:
134 return False
135 # Reject candidates made entirely of stopwords (e.g., "Top Alternatives").
136 if all(tok in _STOPWORD_TOKENS for tok in tokens):
137 return False
138 # Reject candidates that overlap with the topic (e.g., topic="OpenAI"
139 # should not return "OpenAI Alternatives" or "OpenAI", and punctuated
140 # brands like "AT&T", "Node.js", or "Coca-Cola" must not match themselves).
141 if _identity_token_set(tokens) & topic_tokens:
142 return False
143 # Reject too-short one-letter tokens like "I" or single digits.
144 if len(tokens) == 1 and len(tokens[0]) < 2:
145 return False
146 return True
147
148
149 def _normalize_candidate(candidate: str) -> str:
150 """Collapse whitespace and strip trailing punctuation."""
151 return re.sub(r"\s+", " ", candidate).strip(".,;:!?'\"()[] ")
152
153
154 def _extract_peer_entities(
155 items: list[dict], topic: str, limit: int,
156 ) -> list[str]:
157 """Score capitalized candidates across SERP items and return top `limit`.
158
159 Scoring is bag-of-phrases frequency across all items in the input. Ties
160 are broken by first-seen order so the output is deterministic.
161 """
162 topic_tokens = _topic_tokens(topic)
163 counts: Counter[str] = Counter()
164 first_seen: dict[str, int] = {}
165 order = 0
166 # Group candidates into a frequency map keyed by lowercased normalized
167 # form so "xAI" and "xAI" count together regardless of case.
168 canonical: dict[str, str] = {}
169 for item in items:
170 text = f"{item.get('title') or ''} {item.get('snippet') or ''}"
171 for raw in _CAPITALIZED_PHRASE.findall(text):
172 candidate = _normalize_candidate(raw)
173 if not _candidate_ok(candidate, topic_tokens):
174 continue
175 key = candidate.lower()
176 if key not in canonical:
177 canonical[key] = candidate
178 first_seen[key] = order
179 order += 1
180 counts[key] += 1
181
182 ranked_keys = sorted(
183 counts.keys(),
184 key=lambda k: (-counts[k], first_seen[k]),
185 )
186 return [canonical[k] for k in ranked_keys[:limit]]
187
188
189 def _queries_for(topic: str) -> dict[str, str]:
190 return {
191 "competitors": f"{topic} competitors",
192 "alternatives": f"{topic} alternatives",
193 "vs": f"{topic} vs",
194 }
195
196
197 _TRAILING_QUALIFIER = re.compile(r"\s*[\(\[][^)\]]*[\)\]]?\s*$")
198
199
200 def _strip_trailing_qualifiers(name: str) -> str:
201 """Drop trailing '(YC W24)' / '[stealth]' tags, including unbalanced leftovers."""
202 cleaned = name
203 while True:
204 next_name = _TRAILING_QUALIFIER.sub("", cleaned)
205 if next_name == cleaned:
206 return cleaned.strip()
207 cleaned = next_name
208
209
210 def _company_name_from_title(title: str) -> str:
211 """Strip listicle suffixes ('Anthropic | Building…', 'Adyen - payments')."""
212 title = title.split("|")[0]
213 for sep in (" — ", " – ", " - "):
214 title = title.split(sep, 1)[0]
215 return _normalize_candidate(_strip_trailing_qualifiers(title))
216
217
218 def _exa_competitors(topic: str, count: int, api_key: str) -> list[str]:
219 """Discover peers from Exa's company index. No publication-date filters."""
220 try:
221 items, _artifact = grounding.exa_company_search(
222 f"companies developing products like {topic} or competing with {topic}",
223 api_key,
224 count=max(count + 3, 8),
225 objective=(
226 f"Find independent companies that compete with {topic} or build "
227 f"similar products. Do not return {topic} itself, subsidiaries, "
228 "or directory and list pages."
229 ),
230 )
231 except Exception as exc:
232 _log(f"Exa company search failed: {exc}")
233 return []
234 topic_tokens = _topic_tokens(topic)
235 names: list[str] = []
236 seen: set[str] = set()
237 for item in items:
238 name = _company_name_from_title(str(item.get("title") or ""))
239 if not _candidate_ok(name, topic_tokens):
240 continue
241 key = name.lower()
242 if key in seen:
243 continue
244 seen.add(key)
245 names.append(name)
246 if len(names) >= count:
247 break
248 return names
249
250
251 def _merge_peer_names(*groups: list[str], limit: int) -> list[str]:
252 """Keep first-seen order across sources, case-insensitive."""
253 merged: list[str] = []
254 seen: set[str] = set()
255 for group in groups:
256 for name in group:
257 key = name.lower()
258 if key in seen:
259 continue
260 seen.add(key)
261 merged.append(name)
262 if len(merged) >= limit:
263 return merged
264 return merged
265
266
267 def _topic_is_company(config: dict, is_company: bool | None) -> bool:
268 """True when the topic is already established as a company, not a person."""
269 if is_company is False:
270 return False
271 company = config.get("_company") if isinstance(config.get("_company"), dict) else {}
272 if company.get("company_via_person"):
273 return False
274 if company.get("company_peer_discovery") == company_resolve.COMPANY_PEER_KEYWORD:
275 return False
276 if is_company is True:
277 return True
278 if company.get("company"):
279 return True
280 return bool(config.get("_company_signal"))
281
282
283 def discover_competitors(
284 topic: str,
285 count: int,
286 config: dict,
287 *,
288 lookback_days: int = 30,
289 is_company: bool | None = None,
290 ) -> list[str]:
291 """Discover `count` peer entities for `topic` via web search.
292
293 When ``EXA_API_KEY`` is set and the topic is a resolved company, Exa's
294 ``company`` category runs first even if Brave (or another backend) is
295 the general web search. Artist and person topics keep keyword SERP
296 mining only. Keyword SERPs fill any remaining slots and are the only
297 path without that key or without a company signal.
298
299 Args:
300 topic: The primary research topic.
301 count: Desired number of competitor entities (1..N).
302 config: Runtime config dict — expects the same shape as the engine
303 config (BRAVE_API_KEY / EXA_API_KEY / SERPER_API_KEY / etc.).
304 lookback_days: Date range for freshness. Defaults to 30.
305 is_company: True when company resolution (or a host company
306 signal) already established this topic as a company. False
307 skips the company index. None reads ``config["_company"]`` /
308 ``config["_company_signal"]``.
309
310 Returns:
311 A list of up to `count` entity names, deduped and ordered by score.
312 Empty list when no web backend is configured or every search fails
313 or returns zero usable candidates.
314 """
315 if count < 1:
316 return []
317 if not _has_backend(config):
318 _log("No web search backend available, skipping competitor discovery")
319 return []
320
321 exa_names: list[str] = []
322 exa_key = grounding.exa_api_key(config)
323 if exa_key and _topic_is_company(config, is_company):
324 exa_names = _exa_competitors(topic, count, exa_key)
325 if len(exa_names) >= count:
326 _log(
327 f"Discovered {len(exa_names)} competitor(s) for {topic!r} "
328 f"via Exa company search: {exa_names}"
329 )
330 return exa_names
331
332 date_range = dates.get_date_range(lookback_days)
333 queries = _queries_for(topic)
334 collected: list[dict] = []
335 searches_run = 0
336
337 def _search(label: str, query: str) -> tuple[str, list[dict]]:
338 items, _artifact = grounding.web_search(query, date_range, config)
339 return label, items
340
341 with ThreadPoolExecutor(max_workers=min(len(queries), MAX_DISCOVERY_WORKERS)) as executor:
342 futures = {
343 executor.submit(_search, label, q): label
344 for label, q in queries.items()
345 }
346 for future in as_completed(futures):
347 label = futures[future]
348 try:
349 _label, items = future.result()
350 collected.extend(items)
351 searches_run += 1
352 except Exception as exc:
353 _log(f"Search failed for {label}: {exc}")
354
355 serp_names = _extract_peer_entities(collected, topic, limit=count) if collected else []
356 entities = _merge_peer_names(exa_names, serp_names, limit=count)
357 if not entities:
358 if not collected and not exa_names:
359 _log(
360 f"No SERP results for {topic!r} across "
361 f"{searches_run}/{len(queries)} queries"
362 )
363 return []
364
365 source = "Exa company search and " if exa_names else ""
366 _log(
367 f"Discovered {len(entities)} competitor(s) for {topic!r} "
368 f"from {source}{searches_run}/{len(queries)} queries: {entities}"
369 )
370 return entities
371
371 lines PYTHON