返回 last30days-skill
relevance.py
根目录 / skills / last30days / scripts / lib / relevance.py
1 """Shared token-overlap relevance scoring for search result ranking.
2
3 The score is intentionally query-centric:
4 - exact phrase matches should score very high
5 - partial matches should pay a meaningful penalty
6 - matches on generic words alone ("odds", "review") should not pass as relevant
7 """
8
9 import re
10 from typing import List, Optional, Set
11
12 from . import cjk
13
14 # Stopwords for relevance computation (common English words that dilute token overlap)
15 STOPWORDS = frozenset({
16 'the', 'a', 'an', 'to', 'for', 'how', 'is', 'in', 'of', 'on',
17 'and', 'with', 'from', 'by', 'at', 'this', 'that', 'it', 'my',
18 'your', 'i', 'me', 'we', 'you', 'what', 'are', 'do', 'can',
19 'its', 'be', 'or', 'not', 'no', 'so', 'if', 'but', 'about',
20 'all', 'just', 'get', 'has', 'have', 'was', 'will',
21 # Hebrew function words / prepositions / conjunctions
22 'את', 'של', 'על', 'עם', 'אל', 'כי', 'לא', 'הוא', 'היא', 'הם',
23 'הן', 'אנו', 'אנחנו', 'זה', 'זו', 'זאת', 'כל', 'יש', 'אין',
24 'כבר', 'רק', 'גם', 'כן', 'אם', 'או', 'אבל', 'כך', 'מה', 'מי',
25 'איך', 'למה', 'כמה', 'היה', 'הייתה', 'היו', 'יהיה', 'יהיו',
26 # Hebrew definite article / prefixes appearing as standalone tokens after split
27 'ה', 'ב', 'ל', 'מ', 'כ', 'ו', 'ש',
28 }) | cjk.CHINESE_STOPWORDS
29
30 # Shared relevance-ranking thresholds for the Reddit pipelines (keyed + keyless).
31 # Single source of truth so both paths apply identical thresholds to the same
32 # query. RELEVANCE_FLOOR: posts below this are off-topic; the zero-overlap tail is
33 # dropped when anything relevant remains. MIN_ON_TOPIC: how many posts must clear
34 # the soft floor before it is applied wholesale.
35 RELEVANCE_FLOOR = 0.1
36 MIN_ON_TOPIC = 5
37 # Generic-only matches (only LOW_SIGNAL_QUERY_TOKENS overlapped) must sit
38 # strictly below RELEVANCE_FLOOR so off-topic hits cannot clear any relevance gate.
39 GENERIC_ONLY_CAP = round(RELEVANCE_FLOOR - 0.01, 2)
40
41
42 # Synonym groups for relevance scoring (bidirectional expansion)
43 # Superset of all platform-specific synonym dicts
44 SYNONYMS = {
45 'hip': {'rap', 'hiphop'},
46 'hop': {'rap', 'hiphop'},
47 'rap': {'hip', 'hop', 'hiphop'},
48 'hiphop': {'rap', 'hip', 'hop'},
49 'js': {'javascript'},
50 'javascript': {'js'},
51 'ts': {'typescript'},
52 'typescript': {'ts'},
53 'ai': {'artificial', 'intelligence'},
54 'ml': {'machine', 'learning'},
55 'react': {'reactjs'},
56 'reactjs': {'react'},
57 'svelte': {'sveltejs'},
58 'sveltejs': {'svelte'},
59 'vue': {'vuejs'},
60 'vuejs': {'vue'},
61 }
62
63 # Generic query words that should not carry relevance on their own.
64 # They still help when paired with stronger entity/topic matches.
65 #
66 # The second group is scaffolding emitted by planner's ranking-query templates
67 # ("What recent evidence from the last 30 days is most relevant to X?" and its
68 # siblings). Those words are not the topic, but every one of them was being
69 # counted as an informative query token, which capped achievable coverage at the
70 # topic's share of the query and demoted on-topic posts. Kept here rather than
71 # stripped in the planner so any caller building a similar natural-language
72 # ranking query gets the same treatment.
73 #
74 # Domain nouns from those same templates (production, market, workflows,
75 # experience, signals, ...) are deliberately absent: they can legitimately be a
76 # user's topic, and demoting them globally would hurt every source.
77 # tests/test_ranking_query_scaffolding.py pins that split.
78 LOW_SIGNAL_QUERY_TOKENS = frozenset({
79 'advice', 'animation', 'animations', 'best', 'chance', 'chances',
80 'code', 'compare', 'comparison', 'differences', 'explain', 'guide',
81 'guides', 'how', 'latest', 'news', 'odds', 'opinion', 'opinions',
82 'prediction', 'predictions', 'probability', 'probabilities', 'prompt',
83 'prompting', 'prompts', 'rate', 'review', 'reviews', 'thoughts',
84 'tip', 'tips', 'tutorial', 'tutorials', 'update', 'updates', 'use',
85 'using', 'versus', 'vs', 'worth',
86 # planner ranking-query scaffolding
87 '30', 'current', 'days', 'describing', 'especially', 'evidence', 'exist',
88 'follow', 'hands', 'last', 'matter', 'most', 'new', 'people', 'real',
89 'recent', 'relevant', 'running', 'up', 'world',
90 })
91
92
93 def tokenize(text: str) -> Set[str]:
94 """Lowercase, strip punctuation, remove stopwords, drop single-char tokens.
95
96 Expands tokens with synonyms for better cross-domain matching.
97
98 Chinese text is segmented via cjk.segment (jieba or character bigrams) so
99 overlap scoring works on Chinese sources; ASCII text keeps the original
100 whitespace path.
101 """
102 words = cjk.segment(text)
103 tokens = {w for w in words if w not in STOPWORDS and len(w) > 1}
104 expanded = set(tokens)
105 for t in tokens:
106 if t in SYNONYMS:
107 expanded.update(SYNONYMS[t])
108 return expanded
109
110
111 def _normalize_phrase(text: str) -> str:
112 """Normalize text for phrase containment checks."""
113 return ' '.join(re.sub(r'[^\w\s]', ' ', text.lower()).split())
114
115
116 class PreparedQuery:
117 """Precomputed query shape reused across items in a stream.
118
119 Built once per ranking_query; reused by token_overlap_relevance so the
120 per-item normalize/score loops don't re-tokenize the same query N times.
121 """
122
123 __slots__ = ("raw", "q_tokens", "informative_q_tokens", "normalized_phrase")
124
125 def __init__(self, query: str) -> None:
126 self.raw = query
127 self.q_tokens = tokenize(query)
128 informative = {t for t in self.q_tokens if t not in LOW_SIGNAL_QUERY_TOKENS}
129 self.informative_q_tokens = informative or self.q_tokens
130 self.normalized_phrase = _normalize_phrase(query)
131
132
133 def _as_prepared(query: "str | PreparedQuery") -> PreparedQuery:
134 return query if isinstance(query, PreparedQuery) else PreparedQuery(query)
135
136
137 def token_overlap_relevance(
138 query: "str | PreparedQuery",
139 text: str,
140 hashtags: Optional[List[str]] = None,
141 ) -> float:
142 """Compute a query-centric relevance score between 0.0 and 1.0.
143
144 The score combines:
145 - query coverage
146 - informative-token coverage
147 - a small precision term to penalize extra noise
148 - an exact phrase bonus
149
150 Generic tokens alone are capped below typical relevance filter thresholds.
151
152 Args:
153 query: Search query
154 text: Content text to match against
155 hashtags: Optional list of hashtags (TikTok/Instagram). Concatenated
156 hashtags are split to match query tokens (e.g. "claudecode" matches "claude").
157
158 Returns:
159 Float between 0.0 and 1.0 (0.5 for empty queries)
160 """
161 prepared = _as_prepared(query)
162 q_tokens = prepared.q_tokens
163
164 # Combine text and hashtags for matching
165 combined = text
166 if hashtags:
167 combined = f"{text} {' '.join(hashtags)}"
168 t_tokens = tokenize(combined)
169
170 # Split concatenated hashtags (e.g., "claudecode" -> matches "claude", "code")
171 if hashtags:
172 for tag in hashtags:
173 tag_lower = tag.lower()
174 for qt in q_tokens:
175 if qt in tag_lower and qt != tag_lower:
176 t_tokens.add(qt)
177
178 if not q_tokens:
179 return 0.5 # Neutral fallback for empty/stopword-only queries
180
181 overlap_tokens = q_tokens & t_tokens
182 overlap = len(overlap_tokens)
183 if overlap == 0:
184 return 0.0
185
186 informative_q_tokens = prepared.informative_q_tokens
187
188 coverage = overlap / len(q_tokens)
189 informative_overlap = len(informative_q_tokens & t_tokens) / len(informative_q_tokens)
190 precision_denominator = min(len(t_tokens), len(q_tokens) + 4) or 1
191 precision = overlap / precision_denominator
192
193 phrase_bonus = 0.0
194 normalized_query = prepared.normalized_phrase
195 normalized_text = _normalize_phrase(combined)
196 if normalized_query:
197 contained = normalized_query in normalized_text
198 if not contained and cjk.has_cjk(normalized_query):
199 # CJK has no inter-word spaces, so a multi-token Chinese query like
200 # "国产大模型 测评" never appears verbatim in continuous source text
201 # ("...国产大模型的最新测评"). Retry the containment with spaces
202 # removed so the phrase bonus isn't permanently dead for Chinese.
203 # Gated on has_cjk so English ("react hooks") keeps space-sensitive
204 # matching and doesn't gain spurious bonuses from concatenation.
205 contained = normalized_query.replace(" ", "") in normalized_text.replace(" ", "")
206 if contained:
207 phrase_bonus = 0.12 if len(normalized_query.split()) > 1 else 0.16
208
209 base = (
210 0.55 * (coverage ** 1.35) +
211 0.25 * informative_overlap +
212 0.20 * precision
213 )
214
215 # If we only matched generic query words, keep the score strictly below
216 # RELEVANCE_FLOOR so these do not survive any relevance filter by default.
217 if informative_q_tokens and not (informative_q_tokens & t_tokens):
218 return round(min(GENERIC_ONLY_CAP, base), 2)
219
220 return round(min(1.0, base + phrase_bonus), 2)
221
221 lines PYTHON