返回 last30days-skill
query.py
根目录 / skills / last30days / scripts / lib / query.py
1 """Shared query preprocessing utilities: noise-word stripping, core subject
2 extraction, and compound term detection. Used by all search modules."""
3
4 import re
5 from typing import FrozenSet, List, Optional, Set
6
7 # Common multi-word prefixes stripped from all queries (identical across modules)
8 PREFIXES = [
9 'what are the best', 'what is the best', 'what are the latest',
10 'what are people saying about', 'what do people think about',
11 'how do i use', 'how do you use', 'how can i use', 'how to use',
12 'how do you', 'how can i', 'how to',
13 'what are', 'what is', 'tips for', 'best practices for',
14 # Hebrew question/meta prefixes
15 'מה יש חדש ב', 'מה יש חדש על', 'מה אנשים אומרים על',
16 'מה חדש ב', 'מה חדש על', 'איך להשתמש ב',
17 'מהם המוצרים של', 'מה הם', 'מהם',
18 ]
19
20 # Multi-word suffixes (used by bird_x)
21 SUFFIXES = [
22 'best practices', 'use cases', 'prompt techniques',
23 'prompting techniques', 'prompting tips',
24 ]
25
26 # Base noise words shared across most modules
27 NOISE_WORDS = frozenset({
28 # Articles/prepositions/conjunctions
29 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'and', 'or',
30 'of', 'in', 'on', 'for', 'with', 'about', 'to',
31 # Question words
32 'how', 'what', 'which', 'who', 'why', 'when', 'where',
33 'does', 'should', 'could', 'would',
34 # Research/meta descriptors
35 'best', 'top', 'good', 'great', 'awesome', 'killer',
36 'latest', 'new', 'news', 'update', 'updates',
37 'trendiest', 'trending', 'hottest', 'hot', 'popular', 'viral',
38 'practices', 'features', 'guide', 'tutorial',
39 'recommendations', 'advice', 'review', 'reviews',
40 'usecases', 'examples', 'comparison', 'versus', 'vs',
41 'plugin', 'plugins', 'skill', 'skills', 'tool', 'tools',
42 # Prompting meta words
43 'prompt', 'prompts', 'prompting', 'techniques', 'tips',
44 'tricks', 'methods', 'strategies', 'approaches',
45 # Action words
46 'using', 'uses', 'use',
47 # Misc filler
48 'people', 'saying', 'think', 'said', 'lately',
49 # Hebrew function words / prepositions / filler
50 'מה', 'מי', 'איך', 'למה', 'איפה', 'מתי', 'כמה', 'האם',
51 'של', 'על', 'עם', 'אל', 'את', 'בין', 'כי', 'כן', 'לא',
52 'יש', 'אין', 'כבר', 'רק', 'גם', 'אבל', 'כך', 'זה', 'זו',
53 'חדש', 'חדשים', 'טוב', 'טובים', 'הכי', 'ביותר',
54 'מוצרים', 'מבצע', 'מבצעים', 'חדשות', 'עדכונים',
55 })
56
57
58 # Shared noise sets for adapter `_extract_core_subject` wrappers.
59 #
60 # SOCIAL_NOISE: short-form micro-social platforms (Bluesky, Threads, Truth Social)
61 # where research/meta words rarely appear in the body of a post.
62 SOCIAL_NOISE = frozenset({
63 'best', 'top', 'good', 'great', 'awesome',
64 'latest', 'new', 'news', 'update', 'updates',
65 'trending', 'hottest', 'popular', 'viral',
66 'practices', 'features', 'recommendations', 'advice',
67 'or', 'and',
68 })
69
70 # VIRAL_NOISE: viral / discovery platforms (TikTok, Instagram, Pinterest) and
71 # the base for YouTube. Adds 'killer', the prompt-meta cluster, and the
72 # methodology cluster on top of SOCIAL_NOISE.
73 VIRAL_NOISE = SOCIAL_NOISE | frozenset({
74 'killer',
75 'prompt', 'prompts', 'prompting',
76 'methods', 'strategies', 'approaches',
77 })
78
79
80 def extract_core_subject(
81 topic: str,
82 *,
83 noise: Optional[FrozenSet[str]] = None,
84 max_words: Optional[int] = None,
85 strip_suffixes: bool = False,
86 ) -> str:
87 """Extract core subject from a verbose search query.
88
89 Strips common question/meta prefixes and noise words to produce a
90 compact search-friendly query. Platforms customize via parameters.
91
92 Args:
93 topic: Raw user query
94 noise: Override noise word set (default: NOISE_WORDS)
95 max_words: Cap result to N words (default: no cap)
96 strip_suffixes: Also strip trailing multi-word suffixes (bird_x uses this)
97
98 Returns:
99 Cleaned query string
100 """
101 text = topic.lower().strip()
102 if not text:
103 return text
104 # Drop the question's closing punctuation first, so that it neither keeps
105 # the last word from matching a suffix or noise word nor survives the
106 # max_words path ("What is Claude Code?" -> "claude code", not "claude code?")
107 text = text.rstrip('?!.').strip() or text
108
109 # Phase 1: Strip multi-word prefixes (longest first, stop after first match)
110 for p in PREFIXES:
111 if text.startswith(p + ' '):
112 text = text[len(p):].strip()
113 break
114
115 # Phase 2: Strip multi-word suffixes (opt-in)
116 if strip_suffixes:
117 for s in SUFFIXES:
118 if text.endswith(' ' + s):
119 text = text[:-len(s)].strip()
120 break
121
122 # Phase 3: Filter individual noise words
123 noise_set = noise if noise is not None else NOISE_WORDS
124 words = text.split()
125 filtered = [w for w in words if w not in noise_set]
126
127 # Apply word cap if requested
128 if max_words is not None and filtered:
129 filtered = filtered[:max_words]
130
131 result = ' '.join(filtered) if filtered else text
132 return result.rstrip('?!.') if not max_words else (result or topic.lower().strip())
133
134
135 def infer_query_intent(topic: str) -> str:
136 """Classify a topic into a coarse intent for adapter query expansion.
137
138 Returns one of: ``comparison``, ``how_to``, ``opinion``, ``product``,
139 ``prediction``, ``breaking_news`` (default).
140
141 The ``how_to`` regex covers both prefixed forms (``how to install``)
142 and bare imperatives (``configure``, ``troubleshoot``, ``debug``,
143 ``fix``). Adapters that previously kept their own copy of this
144 classifier had drifted to subtly different word lists; this is the
145 superset.
146
147 Polymarket keeps a custom narrower classifier (prediction-only) and
148 does NOT delegate here; its expansion only needs that signal.
149 """
150 text = topic.lower().strip()
151 if re.search(r"\b(vs|versus|compare|difference between)\b", text):
152 return "comparison"
153 if re.search(
154 r"\b(how to|tutorial|guide|setup|step by step|deploy|install|"
155 r"configuration|configure|troubleshoot|troubleshooting|error|errors|"
156 r"fix|debug)\b",
157 text,
158 ):
159 return "how_to"
160 if re.search(r"\b(thoughts on|worth it|should i|opinion|review)\b", text):
161 return "opinion"
162 if re.search(r"\b(pricing|feature|features|best .* for)\b", text):
163 return "product"
164 if re.search(r"\b(predict|prediction|odds|forecast|chance)\b", text):
165 return "prediction"
166 return "breaking_news"
167
168
169 _COMPOUND_BRAND_TOKEN = r'(?:[A-Z][A-Za-z0-9]*|[a-z]+[A-Z][A-Za-z0-9]*)'
170 _COMPOUND_BRAND_TOKEN_RE = re.compile(rf'^{_COMPOUND_BRAND_TOKEN}$')
171 # Unicode- and symbol-safe boundaries: reject mid-word slices across non-ASCII
172 # letters (\w), dotted brands (Next.JS), straight/curly apostrophes (O'Reilly,
173 # O’Reilly), ampersands (AT&T), hyphens (Multi-Agent), and symbol suffixes
174 # (C++, C#), while still allowing trailing sentence punctuation like periods
175 # not followed by a word character.
176 _COMPOUND_CAPITALIZED_RUN_RE = re.compile(
177 rf"(?<![\w'.\u2019+#&-])(?:{_COMPOUND_BRAND_TOKEN}\s+)+{_COMPOUND_BRAND_TOKEN}"
178 rf"(?![\w'\u2019+#&-]|\.\w)"
179 )
180 COMPOUND_ENTITY_PHRASE_RE = re.compile(
181 rf"^{_COMPOUND_BRAND_TOKEN}(?:\s+{_COMPOUND_BRAND_TOKEN}){{1,2}}$"
182 )
183 _COMPOUND_EDGE_NOISE = NOISE_WORDS | frozenset({
184 'i', 'you', 'we', 'my', 'your', 'our', 'me', 'can', 'do', 'did',
185 'this', 'that', 'from',
186 'free', 'cheap', 'recommended', 'favorite', 'favourite',
187 'alternative', 'alternatives',
188 'workflow', 'workflows',
189 'example', 'tutorials',
190 'application', 'applications',
191 'practice', 'production',
192 'case', 'cases',
193 })
194 # Question and research/meta words that never open a brand name and are always
195 # trimmed from the start of a capitalized run.
196 _UNAMBIGUOUS_LEADING_PROMPT_WORDS = frozenset({
197 'how', 'what', 'which', 'who', 'why', 'when', 'where',
198 'does', 'do', 'did', 'should', 'could', 'would', 'can',
199 'is', 'are', 'was', 'were',
200 'i', 'you', 'we', 'my', 'your', 'our', 'me',
201 'using', 'uses', 'use',
202 'latest', 'trending', 'trendiest', 'hottest', 'popular', 'viral',
203 'compare', 'versus', 'vs', 'comparison',
204 'alternative', 'alternatives',
205 'review', 'reviews', 'guide', 'tutorial', 'tutorials',
206 'tips', 'tricks', 'recommendations', 'advice',
207 'news', 'update', 'updates',
208 })
209 _QUESTION_STARTERS = frozenset({'how', 'what', 'which', 'who', 'why', 'when', 'where'})
210 # Soft leading fillers trimmed only when 3+ words remain (e.g. "Best GitHub
211 # Actions" -> "GitHub Actions", "Best React Native Tips" -> "React Native"),
212 # keeping 2-word brands ("Best Buy", "Best Egg", "The Verge") and "New"/"On"-
213 # prefixed multi-word brands ("New Balance", "New York Times", "On Running",
214 # "On Running Cloudmonster") intact.
215 _SOFT_LEADING_NOISE = (
216 _COMPOUND_EDGE_NOISE - _UNAMBIGUOUS_LEADING_PROMPT_WORDS - frozenset({'new', 'on'})
217 )
218 _TITLE_CASE_CONNECTORS = frozenset({
219 'a', 'an', 'the', 'for', 'of', 'in', 'on', 'to', 'with', 'and', 'or', 'vs',
220 })
221 _ENTITY_JOINERS = frozenset({'and', 'or', 'vs'})
222
223
224 def _is_capitalized_or_brand(tok: str) -> bool:
225 return tok[0].isupper() or _COMPOUND_BRAND_TOKEN_RE.fullmatch(tok) is not None
226
227
228 def _is_title_cased_prompt(topic: str) -> bool:
229 """True when a topic uses Title Case across the whole prompt, leaving no
230 case signal to distinguish proper nouns from prompt framing.
231
232 Recognizes:
233 - 4+ word strict every-word Title Case ("Best AI Coding Tools For Python
234 Developers", "Hermes Agent Actual Use Cases")
235 - 3+ word Title-Cased question/how-to prompts starting with a question word
236 ("How to Install Docker", "What Is Docker")
237 - Standard English Title Case with lowercase minor connectors and at least
238 4 capitalized words ("Best AI Coding Tools for Python Developers"), while
239 keeping short brand-plus-subject queries ("The Verge on AI") and bare
240 entity comparisons/lists ("Claude Code and React Native", "New Balance vs
241 On Running", "Best Buy vs Target") eligible.
242 """
243 alpha_words = [
244 tok for tok in re.findall(r"\w+(?:['\u2019-]\w+)*", topic)
245 if tok[0].isalpha()
246 ]
247 if len(alpha_words) < 3:
248 return False
249 all_capped = all(_is_capitalized_or_brand(tok) for tok in alpha_words)
250 if all_capped and len(alpha_words) >= 4:
251 return True
252 lowercase_words = [tok for tok in alpha_words if not _is_capitalized_or_brand(tok)]
253 if not all(tok in _TITLE_CASE_CONNECTORS for tok in lowercase_words):
254 return False
255 if alpha_words[0].lower() in _QUESTION_STARTERS:
256 return True
257 if len(alpha_words) < 4:
258 return False
259 non_connector_words = [tok for tok in alpha_words if tok not in _TITLE_CASE_CONNECTORS]
260 if len(non_connector_words) < 4:
261 return False
262 if all(tok in _ENTITY_JOINERS for tok in lowercase_words) and not any(
263 tok.lower() in _UNAMBIGUOUS_LEADING_PROMPT_WORDS for tok in non_connector_words
264 ):
265 return False
266 return True
267
268
269 def extract_compound_terms(topic: str) -> List[str]:
270 """Detect multi-word terms that should be quoted in search queries.
271
272 Identifies:
273 - Hyphenated terms: "multi-agent", "vc-backed"
274 - Short capitalized/brand multi-word names (2-3 words): "Claude Code",
275 "React Native", "GitHub Actions", "MacBook Pro", "DeepSeek R1",
276 "iPhone Pro", "New Balance", "On Running", "Best Buy", "Best Egg",
277 "The Verge"
278
279 Anchored to full Unicode/symbol-safe word boundaries so PascalCase and
280 camelCase brands are never sliced mid-word, requires mixed-case brand
281 tokens (avoiding ALL-CAPS generic phrases like "Best VPN" / "Top CRM"),
282 and skips full Title-Cased prompts or runs longer than 3 words after
283 trimming noise/intent-modifier edges.
284 """
285 terms: List[str] = []
286
287 # Hyphenated terms
288 for match in re.finditer(r'\b\w+-\w+(?:-\w+)*\b', topic):
289 terms.append(match.group())
290
291 if _is_title_cased_prompt(topic):
292 return terms
293
294 # Word-bounded capitalized / brand sequences (2-3 words after edge trim)
295 for match in _COMPOUND_CAPITALIZED_RUN_RE.finditer(topic):
296 words = match.group().split()
297 while words and (
298 words[0].lower() in _UNAMBIGUOUS_LEADING_PROMPT_WORDS
299 or (len(words) > 2 and words[0].lower() in _SOFT_LEADING_NOISE)
300 ):
301 words.pop(0)
302 while words and words[-1].lower() in _COMPOUND_EDGE_NOISE:
303 words.pop()
304 if (
305 len(words) == 2
306 and words[0].lower() in _COMPOUND_EDGE_NOISE
307 and words[1].isupper()
308 ):
309 continue
310 if (
311 2 <= len(words) <= 3
312 and not all(len(w) == 1 for w in words)
313 and not all(w.lower() in _COMPOUND_EDGE_NOISE for w in words)
314 ):
315 phrase = " ".join(words)
316 if phrase not in terms:
317 terms.append(phrase)
318
319 return terms
320
321
322 def leading_mentions(text: Optional[str]) -> List[str]:
323 """Return the handles a post is directed at: the leading run of @mentions in the text.
324
325 X replies open with the target handle(s) (e.g. "@someone thanks!"), so the
326 leading run identifies who the post is addressed to. A mention later in the
327 body is not a reply target and is intentionally ignored. Returns normalized
328 (``@``-stripped, lowercased) handles, in order. Shared by every X-shaped
329 source adapter (bird, xquik) so leading-mention parsing has one definition.
330 """
331 out: List[str] = []
332 for token in (text or "").split():
333 tok = token.strip(",.:;!?")
334 if tok.startswith("@") and len(tok) > 1:
335 out.append(tok[1:].lower())
336 else:
337 break
338 return out
339
339 lines PYTHON