返回 last30days-skill
relevance.rs
根目录 / rust / crates / last30days-core / src / relevance.rs
1 //! Query-centric token-overlap relevance scoring.
2 //!
3 //! Mirrors `skills/last30days/scripts/lib/relevance.py`.
4
5 use std::collections::BTreeSet;
6
7 use crate::cjk;
8 use crate::dedupe;
9
10 /// Shared relevance floor below which posts are treated as off-topic.
11 pub const RELEVANCE_FLOOR: f64 = 0.1;
12
13 /// Cap applied when only generic low-signal tokens overlapped (`0.09`).
14 pub const GENERIC_ONLY_CAP: f64 = 0.09;
15
16 /// English and Hebrew stopwords excluded from relevance tokenization.
17 pub const STOPWORDS: &[&str] = &[
18 "the",
19 "a",
20 "an",
21 "to",
22 "for",
23 "how",
24 "is",
25 "in",
26 "of",
27 "on",
28 "and",
29 "with",
30 "from",
31 "by",
32 "at",
33 "this",
34 "that",
35 "it",
36 "my",
37 "your",
38 "i",
39 "me",
40 "we",
41 "you",
42 "what",
43 "are",
44 "do",
45 "can",
46 "its",
47 "be",
48 "or",
49 "not",
50 "no",
51 "so",
52 "if",
53 "but",
54 "about",
55 "all",
56 "just",
57 "get",
58 "has",
59 "have",
60 "was",
61 "will", // Hebrew function words
62 "את",
63 "של",
64 "על",
65 "עם",
66 "אל",
67 "כי",
68 "לא",
69 "הוא",
70 "היא",
71 "הם",
72 "הן",
73 "אנו",
74 "אנחנו",
75 "זה",
76 "זו",
77 "זאת",
78 "כל",
79 "יש",
80 "אין",
81 "כבר",
82 "רק",
83 "גם",
84 "כן",
85 "אם",
86 "או",
87 "אבל",
88 "כך",
89 "מה",
90 "מי",
91 "איך",
92 "למה",
93 "כמה",
94 "היה",
95 "הייתה",
96 "היו",
97 "יהיה",
98 "יהיו",
99 // Hebrew single-letter prefixes
100 "ה",
101 "ב",
102 "ל",
103 "מ",
104 "כ",
105 "ו",
106 "ש",
107 ];
108
109 /// Generic query words that cannot carry relevance on their own.
110 pub const LOW_SIGNAL_QUERY_TOKENS: &[&str] = &[
111 "advice",
112 "animation",
113 "animations",
114 "best",
115 "chance",
116 "chances",
117 "code",
118 "compare",
119 "comparison",
120 "differences",
121 "explain",
122 "guide",
123 "guides",
124 "how",
125 "latest",
126 "news",
127 "odds",
128 "opinion",
129 "opinions",
130 "prediction",
131 "predictions",
132 "probability",
133 "probabilities",
134 "prompt",
135 "prompting",
136 "prompts",
137 "rate",
138 "review",
139 "reviews",
140 "thoughts",
141 "tip",
142 "tips",
143 "tutorial",
144 "tutorials",
145 "update",
146 "updates",
147 "use",
148 "using",
149 "versus",
150 "vs",
151 "worth",
152 // Planner ranking-query scaffolding
153 "30",
154 "current",
155 "days",
156 "describing",
157 "especially",
158 "evidence",
159 "exist",
160 "follow",
161 "hands",
162 "last",
163 "matter",
164 "most",
165 "new",
166 "people",
167 "real",
168 "recent",
169 "relevant",
170 "running",
171 "up",
172 "world",
173 ];
174
175 /// Returns synonym expansions for `token`, matching `relevance.SYNONYMS`.
176 pub fn synonyms_for(token: &str) -> &'static [&'static str] {
177 match token {
178 "hip" | "hop" => &["rap", "hiphop"],
179 "rap" => &["hip", "hop", "hiphop"],
180 "hiphop" => &["rap", "hip", "hop"],
181 "js" => &["javascript"],
182 "javascript" => &["js"],
183 "ts" => &["typescript"],
184 "typescript" => &["ts"],
185 "ai" => &["artificial", "intelligence"],
186 "ml" => &["machine", "learning"],
187 "react" => &["reactjs"],
188 "reactjs" => &["react"],
189 "svelte" => &["sveltejs"],
190 "sveltejs" => &["svelte"],
191 "vue" => &["vuejs"],
192 "vuejs" => &["vue"],
193 _ => &[],
194 }
195 }
196
197 /// Returns `true` if `token` is a relevance stopword.
198 #[inline]
199 pub fn is_stopword(token: &str) -> bool {
200 STOPWORDS.contains(&token) || cjk::is_chinese_stopword(token)
201 }
202
203 /// Returns `true` if `token` is a low-signal generic query word.
204 #[inline]
205 pub fn is_low_signal(token: &str) -> bool {
206 LOW_SIGNAL_QUERY_TOKENS.contains(&token)
207 }
208
209 /// Lowercases, segments, removes stopwords and single-char tokens, and expands synonyms.
210 pub fn tokenize(text: &str) -> BTreeSet<String> {
211 let mut base = BTreeSet::new();
212 for word in cjk::segment(text) {
213 if word.chars().nth(1).is_some() && !is_stopword(&word) {
214 base.insert(word);
215 }
216 }
217 let mut expanded = base.clone();
218 for token in &base {
219 for &syn in synonyms_for(token) {
220 expanded.insert(syn.to_owned());
221 }
222 }
223 expanded
224 }
225
226 /// Precomputed query representation reused across items in a stream.
227 #[derive(Debug, Clone, PartialEq, Eq)]
228 pub struct PreparedQuery {
229 raw: String,
230 q_tokens: BTreeSet<String>,
231 informative_q_tokens: BTreeSet<String>,
232 normalized_phrase: String,
233 phrase_has_cjk: bool,
234 phrase_no_spaces: String,
235 phrase_word_count: usize,
236 }
237
238 impl PreparedQuery {
239 /// Builds a [`PreparedQuery`] from a raw search or ranking query.
240 pub fn new(query: &str) -> Self {
241 let q_tokens = tokenize(query);
242 let informative: BTreeSet<String> = q_tokens
243 .iter()
244 .filter(|t| !is_low_signal(t))
245 .cloned()
246 .collect();
247 let informative_q_tokens = if informative.is_empty() {
248 q_tokens.clone()
249 } else {
250 informative
251 };
252 let normalized_phrase = dedupe::normalize_text(query);
253 let phrase_has_cjk = cjk::has_cjk(&normalized_phrase);
254 let phrase_no_spaces = if phrase_has_cjk {
255 normalized_phrase.replace(' ', "")
256 } else {
257 String::new()
258 };
259 let phrase_word_count = normalized_phrase.split_whitespace().count();
260 Self {
261 raw: query.to_owned(),
262 q_tokens,
263 informative_q_tokens,
264 normalized_phrase,
265 phrase_has_cjk,
266 phrase_no_spaces,
267 phrase_word_count,
268 }
269 }
270
271 /// Returns the original raw query string.
272 pub fn raw(&self) -> &str {
273 &self.raw
274 }
275
276 /// Returns the expanded query token set.
277 pub fn tokens(&self) -> &BTreeSet<String> {
278 &self.q_tokens
279 }
280
281 /// Returns the informative (non-generic) query token set.
282 pub fn informative_tokens(&self) -> &BTreeSet<String> {
283 &self.informative_q_tokens
284 }
285
286 /// Returns the normalized phrase used for exact phrase bonus checks.
287 pub fn normalized_phrase(&self) -> &str {
288 &self.normalized_phrase
289 }
290 }
291
292 #[inline]
293 #[expect(
294 clippy::as_conversions,
295 clippy::cast_precision_loss,
296 reason = "token counts are bounded by item length and convert cleanly to f64"
297 )]
298 fn usize_to_f64(value: usize) -> f64 {
299 value as f64
300 }
301
302 /// Rounds `value` to 2 decimal places using banker's rounding (matches Python `round(x, 2)`).
303 #[inline]
304 pub(crate) fn round_2(value: f64) -> f64 {
305 (value * 100.0).round_ties_even() / 100.0
306 }
307
308 /// Computes a query-centric relevance score in `[0.0, 1.0]` (`0.5` for empty queries).
309 pub fn token_overlap_relevance(query: &PreparedQuery, text: &str, hashtags: &[String]) -> f64 {
310 let combined_owned;
311 let combined: &str = if hashtags.is_empty() {
312 text
313 } else {
314 let mut buf = String::with_capacity(
315 text.len() + 1 + hashtags.iter().map(|h| h.len() + 1).sum::<usize>(),
316 );
317 buf.push_str(text);
318 for tag in hashtags {
319 buf.push(' ');
320 buf.push_str(tag);
321 }
322 combined_owned = buf;
323 &combined_owned
324 };
325
326 let mut t_tokens = tokenize(combined);
327
328 if !hashtags.is_empty() {
329 for tag in hashtags {
330 let tag_lower = tag.to_lowercase();
331 for qt in &query.q_tokens {
332 if tag_lower.contains(qt.as_str()) && qt.as_str() != tag_lower.as_str() {
333 t_tokens.insert(qt.clone());
334 }
335 }
336 }
337 }
338
339 if query.q_tokens.is_empty() {
340 return 0.5;
341 }
342
343 let overlap = query.q_tokens.intersection(&t_tokens).count();
344 if overlap == 0 {
345 return 0.0;
346 }
347
348 let informative_hits = query.informative_q_tokens.intersection(&t_tokens).count();
349 let coverage = usize_to_f64(overlap) / usize_to_f64(query.q_tokens.len());
350 let informative_overlap =
351 usize_to_f64(informative_hits) / usize_to_f64(query.informative_q_tokens.len());
352 let precision_denom = t_tokens.len().min(query.q_tokens.len() + 4).max(1);
353 let precision = usize_to_f64(overlap) / usize_to_f64(precision_denom);
354
355 let mut phrase_bonus = 0.0;
356 if !query.normalized_phrase.is_empty() {
357 let normalized_text = dedupe::normalize_text(combined);
358 let mut contained = normalized_text.contains(&query.normalized_phrase);
359 if !contained && query.phrase_has_cjk {
360 let stripped_text = normalized_text.replace(' ', "");
361 contained = stripped_text.contains(&query.phrase_no_spaces);
362 }
363 if contained {
364 phrase_bonus = if query.phrase_word_count > 1 {
365 0.12
366 } else {
367 0.16
368 };
369 }
370 }
371
372 let base = 0.55 * coverage.powf(1.35) + 0.25 * informative_overlap + 0.20 * precision;
373
374 if !query.informative_q_tokens.is_empty() && informative_hits == 0 {
375 return round_2(GENERIC_ONLY_CAP.min(base));
376 }
377
378 round_2((base + phrase_bonus).min(1.0))
379 }
380
380 lines RUST