SPB Git

Repository Public

lib.rs 20.4 KB 447 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SPSearch9// File             : crates/ranking/src/lib.rs10// Module           : crates11// Repository       : https://git.spboucher.ai/spweb12// Project Website  : https://search.spboucher.ai13// Created          : 2026-11-2714// Last Modified    : 2026-12-0115//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//! Classement final : BM25 pondéré par champ (calculé par les shards) × qualité × fraîcheur × signaux89//! de navigation, puis déduplication et diversité par domaine. Les poids sont versionnés.9091use serde::Serialize;92use spweb_protocol::Hit;9394pub mod v2;9596pub const WEIGHTS_VERSION: &str = "rank-v3";9798#[derive(Debug, Clone)]99pub struct Weights {100    pub quality: f32,101    pub freshness: f32,102    pub freshness_intent: f32,103    pub freshness_half_life_days: f32,104    pub title_all_terms: f32,105    pub domain_match: f32,106    pub root_page: f32,107    pub lang_match: f32,108    /// Poids de l'autorité du domaine (graphe des domaines). Borné : la popularité n'est pas une preuve de fiabilité.109    pub authority: f32,110    /// Nom de site correspondant à un seul terme de la requête (« ville de gatineau » -> gatineau.ca).111    pub domain_match_weak: f32,112    /// Titre qui se résume à la requête (part des mots du titre couverts par la requête).113    pub title_precision: f32,114    /// Page d'accueil d'un site dont le nom reprend toute la requête : l'intention de navigation est nette.115    pub site_home: f32,116    /// Site de la région de l'utilisateur (pays déduit du suffixe du domaine). Signal modéré : il départage,117    /// il n'écarte jamais un bon résultat étranger.118    pub region: f32,119    /// Supplément pour la province ou le sous-ensemble demandé (ex. `ca-qc` : domaines québécois).120    pub subregion: f32,121    pub max_per_domain: usize,122}123124impl Default for Weights {125    fn default() -> Self {126        Weights {127            quality: 0.9,128            freshness: 0.10,129            freshness_intent: 0.45,130            freshness_half_life_days: 30.0,131            title_all_terms: 0.20,132            domain_match: 0.90,133            root_page: 0.10,134            lang_match: 0.08,135            authority: 0.60,136            domain_match_weak: 0.30,137            title_precision: 0.30,138            site_home: 1.5,139            region: 0.35,140            subregion: 0.15,141            max_per_domain: 2,142        }143    }144}145146#[derive(Debug, Clone, Serialize)]147pub struct Ranked {148    #[serde(flatten)]149    pub hit: Hit,150    pub score: f32,151    pub freshness: f32,152    pub explain: String,153}154155const FRESH_WORDS: &[&str] = &[156    "aujourd", "actualite", "actualites", "nouvelles", "news", "latest", "recent", "recents", "today", "breaking", "dernier", "dernieres", "derniere", "maintenant",157];158159pub fn has_freshness_intent(terms: &[&str]) -> bool {160    terms.iter().any(|t| FRESH_WORDS.contains(t) || (t.len() == 4 && t.starts_with("20") && t.chars().all(|c| c.is_ascii_digit())))161}162163fn path_depth(url: &str) -> usize {164    url.split_once("://").map(|x| x.1).unwrap_or(url).split('?').next().unwrap_or("").split('/').skip(1).filter(|s| !s.is_empty()).count()165}166167fn fold_simple(s: &str) -> String {168    spweb_query::fold(s)169}170171/// `terms` : termes positifs repliés de la requête. `ui_lang` : langue préférée de l'utilisateur si connue.172/// Pays (et sous-région) d'un domaine d'après son suffixe. Les suffixes génériques (.com, .org, .net) ne173/// disent rien : `None`.174pub fn domain_region(domain: &str) -> Option<(&'static str, Option<&'static str>)> {175    let d = domain;176    let ends = |s: &str| d == s.trim_start_matches('.') || d.ends_with(s);177    if ends(".qc.ca") || ends(".quebec") || d == "quebec.ca" || d == "montreal.ca" || d == "gatineau.ca" {178        return Some(("ca", Some("qc")));179    }180    for (suffix, country) in [(".ca", "ca"), (".fr", "fr"), (".ch", "ch"), (".be", "be"), (".lu", "lu"), (".us", "us"), (".gov", "us"), (".mil", "us"), (".uk", "gb"), (".de", "de"), (".es", "es"), (".it", "it"), (".nl", "nl"), (".au", "au"), (".nz", "nz"), (".ie", "ie"), (".ma", "ma"), (".sn", "sn"), (".ci", "ci"), (".dz", "dz"), (".tn", "tn"), (".br", "br"), (".mx", "mx"), (".jp", "jp")] {181        if ends(suffix) {182            return Some((country, None));183        }184    }185    None186}187188/// `region` : pays de l'utilisateur (`ca`, `fr`…), éventuellement suivi d'une sous-région (`ca-qc`).189pub fn rank(hits: Vec<Hit>, terms: &[&str], ui_lang: Option<&str>, region: Option<&str>, now: i64, w: &Weights) -> Vec<Ranked> {190    let (user_country, user_sub) = match region.map(|r| r.split_once('-').unwrap_or((r, ""))) {191        Some((c, s)) => (Some(c), if s.is_empty() { None } else { Some(s) }),192        None => (None, None),193    };194    let guesses = spweb_query::site_guesses(terms);195    let intent = has_freshness_intent(terms);196    let fw = if intent { w.freshness_intent } else { w.freshness };197    let mut ranked: Vec<Ranked> = hits198        .into_iter()199        .map(|h| {200            let age_ref = h.published_at.unwrap_or(h.checked_at);201            let age_days = ((now - age_ref).max(0) as f32) / 86_400.0;202            let fresh = (0.5f32).powf(age_days / w.freshness_half_life_days);203            // Sans date de publication vérifiée, la fraîcheur ne vaut que la moitié (une date de contrôle n'est pas une date de publication).204            let fresh_eff = if h.published_at.is_some() { fresh } else { fresh * 0.5 };205            let title = fold_simple(&h.title);206            let title_tokens: Vec<&str> = title.split(|c: char| !c.is_alphanumeric()).filter(|t| !t.is_empty()).collect();207            let all_in_title = !terms.is_empty() && terms.iter().all(|t| title_tokens.contains(t));208            let dom_label = h.domain.split('.').next().unwrap_or("");209            let guess = guesses.iter().find(|g| g.0 == dom_label).map(|g| g.1);210            let dom_match = guess == Some(true);211            let dom_weak = guess == Some(false);212            // Précision du titre : « Université Laval » (2 mots sur 2) vaut mieux qu'un long titre qui contient213            // les mêmes mots parmi d'autres. Les mots vides du titre ne comptent pas.214            let content_title: Vec<&&str> = title_tokens.iter().filter(|t| t.chars().count() > 2).collect();215            let covered = content_title.iter().filter(|t| terms.contains(**t)).count();216            let precision = if content_title.is_empty() { 0.0 } else { covered as f32 / content_title.len() as f32 };217            let depth = path_depth(&h.url);218            let q = h.quality.clamp(0.0, 1.0);219            let mut f = 1.0 + w.quality * (q - 0.5) * 2.0 * 0.5;220            f *= 1.0 + fw * fresh_eff;221            let mut why = format!("bm25={:.3} q={:.2} frais={:.2}", h.bm25, q, fresh_eff);222            if all_in_title {223                f *= 1.0 + w.title_all_terms;224                why.push_str(" +titre");225            }226            if dom_match {227                f *= 1.0 + w.domain_match / (1.0 + depth as f32);228                why.push_str(" +domaine");229                if depth == 0 {230                    // Plusieurs sites peuvent porter le même nom (python.org, python.land) : l'autorité départage.231                    // Le rang centile est très plat en haut de l'échelle, d'où la puissance. Sans autorité connue,232                    // demi-poids.233                    let a = h.authority.clamp(0.0, 1.0);234                    f *= 1.0 + w.site_home * if a > 0.0 { a.powi(12) } else { 0.5 };235                    why.push_str(" +accueil");236                }237            } else if dom_weak {238                f *= 1.0 + w.domain_match_weak / (1.0 + depth as f32);239                why.push_str(" +domaine(terme)");240            }241            if all_in_title && precision > 0.0 {242                f *= 1.0 + w.title_precision * precision;243                why.push_str(&format!(" précision={:.2}", precision));244            }245            if depth == 0 {246                f *= 1.0 + w.root_page * 0.5;247            }248            if let Some(l) = ui_lang {249                if h.lang == l {250                    f *= 1.0 + w.lang_match;251                    why.push_str(" +langue");252                }253            }254            let auth = h.authority.clamp(0.0, 1.0);255            if auth > 0.0 {256                f *= 1.0 + w.authority * auth.powi(4);257                why.push_str(&format!(" autorité={:.2}", auth));258            }259            if let (Some(uc), Some((dc, ds))) = (user_country, domain_region(&h.domain)) {260                if uc == dc {261                    f *= 1.0 + w.region;262                    why.push_str(" +région");263                    if user_sub.is_some() && user_sub == ds {264                        f *= 1.0 + w.subregion;265                    }266                }267            }268            let score = h.bm25 * f;269            Ranked { hit: h, score, freshness: fresh_eff, explain: why }270        })271        .collect();272    ranked.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal).then_with(|| a.hit.doc_id.cmp(&b.hit.doc_id)));273274    // Déduplication (même titre + même extrait) puis diversité : au plus `max_per_domain` résultats par275    // domaine dans chaque fenêtre de 10, les suivants sont repoussés (jamais supprimés).276    let mut seen = std::collections::HashSet::new();277    ranked.retain(|r| seen.insert((fold_simple(&r.hit.title), r.hit.snippet.clone())));278    // Même site, même titre : variantes d'une même page (pagination, paramètres) ; seule la mieux classée reste.279    let mut seen_title = std::collections::HashSet::new();280    ranked.retain(|r| seen_title.insert((r.hit.domain.clone(), fold_simple(&r.hit.title))));281    let mut out: Vec<Ranked> = Vec::with_capacity(ranked.len());282    let mut deferred: std::collections::VecDeque<Ranked> = std::collections::VecDeque::new();283    let mut window: std::collections::HashMap<String, usize> = std::collections::HashMap::new();284    let mut it = ranked.into_iter();285    loop {286        if out.len() % 10 == 0 {287            window.clear();288        }289        // d'abord un différé qui tient désormais dans la fenêtre290        let pos = deferred.iter().position(|r| window.get(&r.hit.domain).copied().unwrap_or(0) < w.max_per_domain);291        let next = match pos {292            Some(p) => deferred.remove(p),293            None => None,294        };295        let cand = match next {296            Some(c) => Some(c),297            None => {298                let mut picked = None;299                for r in it.by_ref() {300                    if window.get(&r.hit.domain).copied().unwrap_or(0) < w.max_per_domain {301                        picked = Some(r);302                        break;303                    }304                    deferred.push_back(r);305                }306                picked307            }308        };309        match cand {310            Some(r) => {311                *window.entry(r.hit.domain.clone()).or_insert(0) += 1;312                out.push(r);313            }314            None => {315                if deferred.is_empty() {316                    break;317                }318                // plus rien d'autre : écouler les différés dans l'ordre du score319                window.clear();320                if let Some(r) = deferred.pop_front() {321                    *window.entry(r.hit.domain.clone()).or_insert(0) += 1;322                    out.push(r);323                }324            }325        }326    }327    out328}329330/// Fusion par rangs réciproques (RRF) de listes déjà classées, pour des nœuds dont les statistiques331/// lexicales ne sont pas comparables. Non utilisée quand un seul nœud répond.332pub fn rrf_merge(lists: Vec<Vec<Hit>>, k: f32) -> Vec<Hit> {333    let mut acc: std::collections::HashMap<u128, (f32, Hit)> = std::collections::HashMap::new();334    for list in lists {335        for (rank, h) in list.into_iter().enumerate() {336            let s = 1.0 / (k + rank as f32 + 1.0);337            acc.entry(h.doc_id.0).and_modify(|e| e.0 += s).or_insert((s, h));338        }339    }340    let mut v: Vec<(f32, Hit)> = acc.into_values().collect();341    v.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal).then_with(|| a.1.doc_id.cmp(&b.1.doc_id)));342    v.into_iter()343        .map(|(s, mut h)| {344            h.bm25 = s;345            h346        })347        .collect()348}349350// ------------------------------------------------- métriques d'évaluation351352/// NDCG@k avec jugements gradués (0..3). `ranked` = identifiants retournés, `judged` = (id, gain).353pub fn ndcg_at(ranked: &[String], judged: &[(String, u32)], k: usize) -> f64 {354    let gain = |id: &String| judged.iter().find(|j| &j.0 == id).map(|j| j.1).unwrap_or(0) as f64;355    let dcg: f64 = ranked.iter().take(k).enumerate().map(|(i, id)| (2f64.powf(gain(id)) - 1.0) / ((i + 2) as f64).log2()).sum();356    let mut ideal: Vec<f64> = judged.iter().map(|j| j.1 as f64).collect();357    ideal.sort_by(|a, b| b.partial_cmp(a).unwrap());358    let idcg: f64 = ideal.iter().take(k).enumerate().map(|(i, g)| (2f64.powf(*g) - 1.0) / ((i + 2) as f64).log2()).sum();359    if idcg == 0.0 { 0.0 } else { dcg / idcg }360}361pub fn recall_at(ranked: &[String], judged: &[(String, u32)], k: usize) -> f64 {362    let rel: Vec<&String> = judged.iter().filter(|j| j.1 > 0).map(|j| &j.0).collect();363    if rel.is_empty() {364        return 0.0;365    }366    ranked.iter().take(k).filter(|id| rel.contains(id)).count() as f64 / rel.len() as f64367}368pub fn mrr(ranked: &[String], judged: &[(String, u32)]) -> f64 {369    ranked.iter().position(|id| judged.iter().any(|j| &j.0 == id && j.1 > 0)).map(|p| 1.0 / (p + 1) as f64).unwrap_or(0.0)370}371372#[cfg(test)]373mod tests {374    use super::*;375    use spweb_common::DocId;376    fn hit(url: &str, title: &str, bm25: f32, q: f32, age_days: i64, published: bool) -> Hit {377        let domain = url.split('/').nth(2).unwrap().to_string();378        Hit { doc_id: DocId::from_url(url), bm25, title: title.into(), url: url.into(), domain, snippet: format!("s {}", url), lang: "fr".into(), checked_at: 1_000_000 - age_days * 86400, published_at: if published { Some(1_000_000 - age_days * 86400) } else { None }, quality: q, shard: 0, words: 0, authority: 0.0, tier: 0, site_match: false, ..Default::default() }379    }380    #[test]381    fn quality_and_title_reorder() {382        let hits = vec![hit("https://a.org/x", "divers", 10.0, 0.1, 5, false), hit("https://b.org/y", "tarte aux pommes", 9.5, 0.9, 5, false)];383        let r = rank(hits, &["tarte", "pommes"], None, None, 1_000_000, &Weights::default());384        assert_eq!(r[0].hit.domain, "b.org");385        assert!(r[0].explain.contains("+titre"));386    }387    #[test]388    fn freshness_intent_boosts_recent_published() {389        let hits = vec![hit("https://a.org/old", "budget", 10.0, 0.5, 400, true), hit("https://b.org/new", "budget", 9.0, 0.5, 1, true)];390        let plain = rank(hits.clone(), &["budget"], None, None, 1_000_000, &Weights::default());391        assert_eq!(plain[0].hit.domain, "a.org");392        let fresh = rank(hits, &["budget", "nouvelles"], None, None, 1_000_000, &Weights::default());393        assert_eq!(fresh[0].hit.domain, "b.org");394    }395    #[test]396    fn diversity_caps_domain_and_dedups() {397        let mut hits: Vec<Hit> = (0..6).map(|i| hit(&format!("https://big.org/p{}", i), &format!("t{}", i), 20.0 - i as f32, 0.5, 3, false)).collect();398        hits.push(hit("https://small.org/a", "ta", 5.0, 0.5, 3, false));399        hits.push(hit("https://other.org/a", "tb", 4.0, 0.5, 3, false));400        let mut dup = hit("https://big.org/dup", "t0", 19.5, 0.5, 3, false);401        dup.snippet = hits[0].snippet.clone();402        hits.push(dup);403        let r = rank(hits, &["x"], None, None, 1_000_000, &Weights::default());404        assert_eq!(r.len(), 8); // doublon retiré, rien d'autre perdu405        let first4: Vec<&str> = r.iter().take(4).map(|x| x.hit.domain.as_str()).collect();406        assert_eq!(first4.iter().filter(|d| **d == "big.org").count(), 2);407        assert!(first4.contains(&"small.org") && first4.contains(&"other.org"));408    }409    #[test]410    fn navigational_domain() {411        let hits = vec![hit("https://blog.example/post-on-wikipedia", "wikipedia est grand", 10.0, 0.5, 3, false), hit("https://wikipedia.org/", "Wikipédia", 8.5, 0.5, 3, false)];412        let r = rank(hits, &["wikipedia"], None, None, 1_000_000, &Weights::default());413        assert_eq!(r[0].hit.domain, "wikipedia.org");414    }415    #[test]416    fn metrics() {417        let ranked = vec!["a".to_string(), "b".into(), "c".into()];418        let judged = vec![("b".to_string(), 3), ("z".into(), 2)];419        assert!((mrr(&ranked, &judged) - 0.5).abs() < 1e-9);420        assert!((recall_at(&ranked, &judged, 20) - 0.5).abs() < 1e-9);421        let n = ndcg_at(&ranked, &judged, 10);422        assert!(n > 0.3 && n < 0.7, "{}", n);423        assert_eq!(ndcg_at(&["b".to_string(), "z".into()], &judged, 10), 1.0);424    }425    #[test]426    fn rrf() {427        let a = vec![hit("https://a.org/1", "1", 3.0, 0.5, 1, false), hit("https://a.org/2", "2", 2.0, 0.5, 1, false)];428        let b = vec![hit("https://a.org/2", "2", 9.0, 0.5, 1, false), hit("https://a.org/3", "3", 1.0, 0.5, 1, false)];429        let m = rrf_merge(vec![a, b], 60.0);430        assert_eq!(m[0].url, "https://a.org/2");431        assert_eq!(m.len(), 3);432    }433}434435#[cfg(test)]436mod region_tests {437    use super::*;438    #[test]439    fn regions_from_suffix() {440        assert_eq!(domain_region("ulaval.ca"), Some(("ca", None)));441        assert_eq!(domain_region("banq.qc.ca"), Some(("ca", Some("qc"))));442        assert_eq!(domain_region("service-public.fr"), Some(("fr", None)));443        assert_eq!(domain_region("example.com"), None);444        assert_eq!(domain_region("africa.com"), None);445    }446}447
Files main
Menu

Theme