返回 last30days-skill
dedupe.rs
根目录 / rust / crates / last30days-core / src / dedupe.rs
1 //! Within-source near-duplicate detection using character n-grams and token Jaccard.
2 //!
3 //! Mirrors `skills/last30days/scripts/lib/dedupe.py`. Uses dual 64-bit FNV-1a
4 //! fingerprints stored in sorted deduplicated vectors for fast exact set
5 //! intersections without per-ngram heap allocations.
6
7 use std::collections::BTreeSet;
8
9 use rayon::prelude::*;
10 use serde::{Deserialize, Serialize};
11
12 use crate::cjk;
13 use crate::error::CoreError;
14
15 /// English stopwords excluded from token Jaccard comparisons.
16 pub const ENGLISH_STOPWORDS: &[&str] = &[
17 "the", "a", "an", "to", "for", "how", "is", "in", "of", "on", "and", "with", "from", "by",
18 "at", "this", "that", "it", "what", "are", "do", "can",
19 ];
20
21 /// Default n-gram width used by [`PreparedText`] and [`hybrid_similarity`].
22 pub const DEFAULT_NGRAM_SIZE: usize = 3;
23
24 /// Controls whether a candidate item participates in fuzzy text deduplication.
25 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26 #[serde(rename_all = "snake_case")]
27 #[non_exhaustive]
28 pub enum DedupeMode {
29 /// Keep the item without comparing its text against prior kept items.
30 UrlOnly,
31 /// Compare the item's text against prior kept fuzzy items.
32 Fuzzy,
33 }
34
35 /// One item passed into [`dedupe_kept_indices`].
36 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37 pub struct DedupeEntry {
38 /// Whether this entry participates in fuzzy text deduplication.
39 pub mode: DedupeMode,
40 /// Combined item text (`title`, `body`, `author`, `container`).
41 pub text: String,
42 }
43
44 /// Returns `true` if `token` is a dedupe stopword (English or Chinese).
45 #[inline]
46 pub fn is_stopword(token: &str) -> bool {
47 ENGLISH_STOPWORDS.contains(&token) || cjk::is_chinese_stopword(token)
48 }
49
50 /// Lowercases `text`, replaces non-word/non-whitespace characters with spaces,
51 /// and collapses runs of whitespace into a single ASCII space.
52 pub fn normalize_text(text: &str) -> String {
53 let lowered = text.to_lowercase();
54 let mut out = String::with_capacity(lowered.len());
55 let mut in_space = true;
56 for ch in lowered.chars() {
57 if cjk::is_word_char(ch) {
58 out.push(ch);
59 in_space = false;
60 } else if !in_space {
61 out.push(' ');
62 in_space = true;
63 }
64 }
65 if out.ends_with(' ') {
66 out.pop();
67 }
68 out
69 }
70
71 /// Extracts character n-grams of width `n` from normalized `text`.
72 ///
73 /// # Errors
74 ///
75 /// Returns [`CoreError::InvalidNgramSize`] if `n` is `0`.
76 pub fn ngrams(text: &str, n: usize) -> Result<BTreeSet<String>, CoreError> {
77 if n == 0 {
78 return Err(CoreError::InvalidNgramSize);
79 }
80 let norm = normalize_text(text);
81 let mut set = BTreeSet::new();
82 if norm.is_empty() {
83 return Ok(set);
84 }
85 let offsets: Vec<usize> = norm.char_indices().map(|(i, _)| i).collect();
86 if offsets.len() < n {
87 set.insert(norm);
88 return Ok(set);
89 }
90 for i in 0..=offsets.len() - n {
91 let start = offsets[i];
92 let end = if i + n < offsets.len() {
93 offsets[i + n]
94 } else {
95 norm.len()
96 };
97 set.insert(norm[start..end].to_owned());
98 }
99 Ok(set)
100 }
101
102 /// Computes Jaccard similarity over two ordered string sets.
103 pub fn jaccard_similarity(left: &BTreeSet<String>, right: &BTreeSet<String>) -> f64 {
104 if left.is_empty() || right.is_empty() {
105 return 0.0;
106 }
107 let intersection = left.intersection(right).count();
108 let union = left.len() + right.len() - intersection;
109 if union == 0 {
110 return 0.0;
111 }
112 ratio(intersection, union)
113 }
114
115 /// Computes token Jaccard similarity between two raw texts.
116 pub fn token_jaccard(text_a: &str, text_b: &str) -> f64 {
117 let a = PreparedText::new(text_a);
118 let b = PreparedText::new(text_b);
119 sorted_jaccard(&a.tokens, &b.tokens)
120 }
121
122 /// Computes the maximum of character trigram Jaccard and token Jaccard similarity.
123 pub fn hybrid_similarity(text_a: &str, text_b: &str) -> f64 {
124 let a = PreparedText::new(text_a);
125 let b = PreparedText::new(text_b);
126 a.similarity(&b)
127 }
128
129 /// 64-bit FNV-1a hash with `SplitMix64` finalizer for low-collision, cache-dense fingerprints.
130 #[inline]
131 fn hash_64(bytes: &[u8]) -> u64 {
132 const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
133 const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
134
135 let mut h = FNV_OFFSET;
136 for &b in bytes {
137 h ^= u64::from(b);
138 h = h.wrapping_mul(FNV_PRIME);
139 }
140 h ^= h >> 30;
141 h = h.wrapping_mul(0xbf58_476d_1ce4_e5b9);
142 h ^= h >> 27;
143 h = h.wrapping_mul(0x94d0_49bb_1331_11eb);
144 h ^ (h >> 31)
145 }
146
147 #[inline]
148 #[expect(
149 clippy::as_conversions,
150 clippy::cast_precision_loss,
151 reason = "set cardinalities are bounded by text length and convert cleanly to f64 for Jaccard ratio"
152 )]
153 fn ratio(num: usize, den: usize) -> f64 {
154 (num as f64) / (den as f64)
155 }
156
157 /// Exact Jaccard similarity on two sorted, deduplicated fingerprint slices.
158 pub(crate) fn sorted_jaccard(left: &[u64], right: &[u64]) -> f64 {
159 if left.is_empty() || right.is_empty() {
160 return 0.0;
161 }
162 let mut i = 0;
163 let mut j = 0;
164 let mut inter = 0usize;
165 while i < left.len() && j < right.len() {
166 match left[i].cmp(&right[j]) {
167 std::cmp::Ordering::Less => i += 1,
168 std::cmp::Ordering::Greater => j += 1,
169 std::cmp::Ordering::Equal => {
170 inter += 1;
171 i += 1;
172 j += 1;
173 }
174 }
175 }
176 let union = left.len() + right.len() - inter;
177 if union == 0 {
178 return 0.0;
179 }
180 ratio(inter, union)
181 }
182
183 #[inline]
184 #[expect(
185 clippy::as_conversions,
186 clippy::cast_possible_truncation,
187 clippy::cast_sign_loss,
188 clippy::cast_precision_loss,
189 reason = "threshold is validated in [0.0, 1.0] and total length is a small non-negative integer"
190 )]
191 fn min_required_intersection(total_len: usize, threshold: f64) -> usize {
192 let raw = (threshold * (total_len as f64)) / (1.0 + threshold);
193 (raw.floor() as usize).saturating_sub(1)
194 }
195
196 /// Exact threshold check for sorted Jaccard with cardinality and remaining-element early exits.
197 #[inline]
198 fn sorted_jaccard_at_least(left: &[u64], right: &[u64], threshold: f64) -> bool {
199 if left.is_empty() || right.is_empty() {
200 return threshold <= 0.0;
201 }
202 let len_l = left.len();
203 let len_r = right.len();
204 let min_len = len_l.min(len_r);
205 let max_len = len_l.max(len_r);
206 // Exact upper bound: |A ∩ B| / |A ∪ B| <= min(|A|, |B|) / max(|A|, |B|).
207 if ratio(min_len, max_len) < threshold {
208 return false;
209 }
210 let total = len_l + len_r;
211 let min_needed = min_required_intersection(total, threshold);
212
213 let mut i = 0;
214 let mut j = 0;
215 let mut inter = 0usize;
216 while i < len_l && j < len_r {
217 // Exact early exit: even if every remaining element matched, we cannot reach min_needed.
218 if inter + (len_l - i).min(len_r - j) < min_needed {
219 return false;
220 }
221 match left[i].cmp(&right[j]) {
222 std::cmp::Ordering::Less => i += 1,
223 std::cmp::Ordering::Greater => j += 1,
224 std::cmp::Ordering::Equal => {
225 inter += 1;
226 i += 1;
227 j += 1;
228 }
229 }
230 }
231 let union = total - inter;
232 if union == 0 {
233 return threshold <= 0.0;
234 }
235 ratio(inter, union) >= threshold
236 }
237
238 /// Precomputed trigram and token fingerprint sets for fast repeated similarity checks.
239 #[derive(Debug, Clone, PartialEq, Eq)]
240 pub struct PreparedText {
241 ngrams: Vec<u64>,
242 tokens: Vec<u64>,
243 }
244
245 impl PreparedText {
246 /// Builds a [`PreparedText`] from raw item text.
247 pub fn new(raw: &str) -> Self {
248 let norm = normalize_text(raw);
249 let mut ngrams = Vec::new();
250 if !norm.is_empty() {
251 if norm.is_ascii() {
252 let bytes = norm.as_bytes();
253 if bytes.len() < DEFAULT_NGRAM_SIZE {
254 ngrams.push(hash_64(bytes));
255 } else {
256 ngrams.reserve(bytes.len() - DEFAULT_NGRAM_SIZE + 1);
257 for window in bytes.windows(DEFAULT_NGRAM_SIZE) {
258 ngrams.push(hash_64(window));
259 }
260 }
261 } else {
262 let offsets: Vec<usize> = norm.char_indices().map(|(i, _)| i).collect();
263 if offsets.len() < DEFAULT_NGRAM_SIZE {
264 ngrams.push(hash_64(norm.as_bytes()));
265 } else {
266 ngrams.reserve(offsets.len() - DEFAULT_NGRAM_SIZE + 1);
267 for i in 0..=offsets.len() - DEFAULT_NGRAM_SIZE {
268 let start = offsets[i];
269 let end = if i + DEFAULT_NGRAM_SIZE < offsets.len() {
270 offsets[i + DEFAULT_NGRAM_SIZE]
271 } else {
272 norm.len()
273 };
274 ngrams.push(hash_64(&norm.as_bytes()[start..end]));
275 }
276 }
277 }
278 ngrams.sort_unstable();
279 ngrams.dedup();
280 }
281
282 let mut tokens = Vec::new();
283 cjk::for_each_segmented_lowered(&norm, |tok| {
284 if tok.chars().nth(1).is_some() && !is_stopword(tok) {
285 tokens.push(hash_64(tok.as_bytes()));
286 }
287 });
288 tokens.sort_unstable();
289 tokens.dedup();
290
291 Self { ngrams, tokens }
292 }
293
294 /// Computes hybrid similarity (`max(trigram_jaccard, token_jaccard)`) against `other`.
295 pub fn similarity(&self, other: &Self) -> f64 {
296 sorted_jaccard(&self.ngrams, &other.ngrams).max(sorted_jaccard(&self.tokens, &other.tokens))
297 }
298
299 /// Returns `true` if [`Self::similarity`] is at least `threshold`.
300 #[inline]
301 pub fn similarity_at_least(&self, other: &Self, threshold: f64) -> bool {
302 // Check smaller token set first; if tokens clear threshold, skip trigrams completely.
303 sorted_jaccard_at_least(&self.tokens, &other.tokens, threshold)
304 || sorted_jaccard_at_least(&self.ngrams, &other.ngrams, threshold)
305 }
306 }
307
308 /// Returns the indices of entries that survive fuzzy near-duplicate removal.
309 ///
310 /// Mirrors pass 2 of `dedupe.py:dedupe_items`: entries marked [`DedupeMode::UrlOnly`]
311 /// or with empty text are always kept without entering the fuzzy comparison pool;
312 /// remaining entries are kept only when their similarity to every previously kept
313 /// fuzzy entry is strictly below `threshold`.
314 ///
315 /// # Errors
316 ///
317 /// Returns [`CoreError::InvalidThreshold`] if `threshold` is non-finite or outside `[0.0, 1.0]`.
318 pub fn dedupe_kept_indices(
319 entries: &[DedupeEntry],
320 threshold: f64,
321 ) -> Result<Vec<usize>, CoreError> {
322 if !threshold.is_finite() || !(0.0..=1.0).contains(&threshold) {
323 return Err(CoreError::InvalidThreshold { value: threshold });
324 }
325 let prepared: Vec<Option<PreparedText>> = if entries.len() >= 64 {
326 entries
327 .par_iter()
328 .map(|entry| {
329 if entry.mode == DedupeMode::UrlOnly || entry.text.is_empty() {
330 None
331 } else {
332 Some(PreparedText::new(&entry.text))
333 }
334 })
335 .collect()
336 } else {
337 entries
338 .iter()
339 .map(|entry| {
340 if entry.mode == DedupeMode::UrlOnly || entry.text.is_empty() {
341 None
342 } else {
343 Some(PreparedText::new(&entry.text))
344 }
345 })
346 .collect()
347 };
348
349 let mut kept = Vec::with_capacity(entries.len());
350 let mut kept_prepared: Vec<PreparedText> = Vec::with_capacity(entries.len());
351
352 for (idx, maybe_prep) in prepared.into_iter().enumerate() {
353 let Some(prep) = maybe_prep else {
354 kept.push(idx);
355 continue;
356 };
357 let is_dup = if kept_prepared.len() >= 128 {
358 kept_prepared
359 .par_iter()
360 .any(|existing| prep.similarity_at_least(existing, threshold))
361 } else {
362 kept_prepared
363 .iter()
364 .any(|existing| prep.similarity_at_least(existing, threshold))
365 };
366 if !is_dup {
367 kept.push(idx);
368 kept_prepared.push(prep);
369 }
370 }
371 Ok(kept)
372 }
373
373 lines RUST