Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SPSearch9// File : crates/dedup/src/lib.rs10// Module : crates11// Repository : https://git.spboucher.ai/spweb12// Project Website : https://search.spboucher.ai13// Created : 2026-11-2714// Last Modified : 2026-11-2715//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: contact@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788//! Empreintes : SHA-256 (duplicat exact), SimHash 64 bits (quasi-duplicat), filtre de Bloom par génération.8990use sha2::{Digest, Sha256};9192pub fn content_hash(normalized_text: &str) -> [u8; 16] {93 let h = Sha256::digest(normalized_text.as_bytes());94 let mut out = [0u8; 16];95 out.copy_from_slice(&h[..16]);96 out97}9899fn fnv64(data: &[u8]) -> u64 {100 let mut h: u64 = 0xcbf29ce484222325;101 for b in data {102 h ^= *b as u64;103 h = h.wrapping_mul(0x100000001b3);104 }105 // finalisation (avalanche) pour de meilleurs bits hauts106 h ^= h >> 33;107 h = h.wrapping_mul(0xff51afd7ed558ccd);108 h ^= h >> 33;109 h110}111112/// SimHash sur des bigrammes de mots (texte déjà normalisé : minuscules, blancs écrasés).113pub fn simhash(text: &str) -> u64 {114 let mut v = [0i32; 64];115 let mut prev: Option<&str> = None;116 let mut n = 0u32;117 for w in text.split_whitespace() {118 if let Some(p) = prev {119 let mut buf = Vec::with_capacity(p.len() + w.len() + 1);120 buf.extend_from_slice(p.as_bytes());121 buf.push(b' ');122 buf.extend_from_slice(w.as_bytes());123 let h = fnv64(&buf);124 for (i, slot) in v.iter_mut().enumerate() {125 if (h >> i) & 1 == 1 {126 *slot += 1;127 } else {128 *slot -= 1;129 }130 }131 n += 1;132 }133 prev = Some(w);134 }135 if n == 0 {136 return fnv64(text.as_bytes());137 }138 let mut out = 0u64;139 for (i, slot) in v.iter().enumerate() {140 if *slot > 0 {141 out |= 1 << i;142 }143 }144 out145}146147pub fn hamming(a: u64, b: u64) -> u32 {148 (a ^ b).count_ones()149}150151/// Filtre de Bloom à deux générations : la génération courante reçoit les insertions ; quand elle est152/// pleine, elle devient l'ancienne et une nouvelle démarre. Mémoire bornée, faux positifs possibles :153/// ce n'est JAMAIS la preuve d'un duplicat (la base durable tranche).154pub struct GenBloom {155 bits: usize,156 k: u32,157 cur: Vec<u64>,158 old: Vec<u64>,159 cur_count: usize,160 capacity: usize,161 pub generation: u64,162}163164impl GenBloom {165 /// `capacity` éléments par génération, ~1 % de faux positifs (10 bits/élément, 7 hachages).166 pub fn new(capacity: usize) -> Self {167 let bits = (capacity.max(1024) * 10).next_power_of_two();168 GenBloom { bits, k: 7, cur: vec![0; bits / 64], old: vec![0; bits / 64], cur_count: 0, capacity: capacity.max(1024), generation: 0 }169 }170 fn idx(&self, item: &[u8]) -> impl Iterator<Item = usize> + '_ {171 let h1 = fnv64(item);172 let h2 = fnv64(&h1.to_le_bytes()) | 1;173 let mask = self.bits as u64 - 1;174 (0..self.k).map(move |i| (h1.wrapping_add((i as u64).wrapping_mul(h2)) & mask) as usize)175 }176 pub fn maybe_contains(&self, item: &[u8]) -> bool {177 let pos: Vec<usize> = self.idx(item).collect();178 let hit = |v: &Vec<u64>| pos.iter().all(|p| v[p / 64] >> (p % 64) & 1 == 1);179 hit(&self.cur) || hit(&self.old)180 }181 pub fn insert(&mut self, item: &[u8]) {182 if self.cur_count >= self.capacity {183 std::mem::swap(&mut self.cur, &mut self.old);184 self.cur.iter_mut().for_each(|w| *w = 0);185 self.cur_count = 0;186 self.generation += 1;187 }188 let pos: Vec<usize> = self.idx(item).collect();189 for p in pos {190 self.cur[p / 64] |= 1 << (p % 64);191 }192 self.cur_count += 1;193 }194 pub fn memory_bytes(&self) -> usize {195 self.bits / 8 * 2196 }197}198199#[cfg(test)]200mod tests {201 use super::*;202 #[test]203 fn simhash_near_and_far() {204 let a = "le conseil municipal de la ville a adopté hier soir un nouveau règlement sur le stationnement dans les rues du centre pendant les mois d hiver afin de faciliter le déneigement";205 let b = "le conseil municipal de la ville a adopté hier soir un nouveau règlement sur le stationnement dans les rues du centre pendant les mois d hiver afin de faciliter le déneigement rapide";206 let c = "recette de tarte aux pommes avec une pâte brisée maison beurre farine sucre cannelle et un soupçon de vanille pour un dessert traditionnel servi tiède avec de la crème";207 assert!(hamming(simhash(a), simhash(b)) <= 8, "{}", hamming(simhash(a), simhash(b)));208 assert!(hamming(simhash(a), simhash(c)) > 12, "{}", hamming(simhash(a), simhash(c)));209 assert_eq!(simhash(a), simhash(a));210 }211 #[test]212 fn hash_exact() {213 assert_eq!(content_hash("x"), content_hash("x"));214 assert_ne!(content_hash("x"), content_hash("y"));215 }216 #[test]217 fn bloom_generations() {218 let mut b = GenBloom::new(2000);219 for i in 0..2000u32 {220 b.insert(&i.to_le_bytes());221 }222 assert!((0..2000u32).all(|i| b.maybe_contains(&i.to_le_bytes())));223 let fp = (10_000..20_000u32).filter(|i| b.maybe_contains(&i.to_le_bytes())).count();224 assert!(fp < 400, "faux positifs {}", fp);225 for i in 2000..3000u32 {226 b.insert(&i.to_le_bytes());227 }228 assert!(b.generation >= 1);229 assert!(b.maybe_contains(&100u32.to_le_bytes())); // encore dans l'ancienne génération230 for i in 3000..8100u32 {231 b.insert(&i.to_le_bytes());232 }233 let still = (0..2000u32).filter(|i| b.maybe_contains(&i.to_le_bytes())).count();234 assert!(still < 200, "génération expirée : {}", still);235 }236}237