SPB Git

Repository Public

understand.rs 34.3 KB 530 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SPSearch9// File             : crates/query/src/understand.rs10// Module           : crates11// Repository       : https://git.spboucher.ai/spweb12// Project Website  : https://search.spboucher.ai13// Created          : 2026-12-0114// 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//! Compréhension des requêtes (SearchRank V2, étape 0) : normalisation, langue, mots vides, intention, lieu,89//! variantes contrôlées. Tout est déterministe et local : aucun modèle de langue, aucune dépendance réseau.90//!91//! Le résultat ne remplace pas la requête analysée (`ParsedQuery`, qui porte les filtres et les phrases) : il92//! dit comment la chercher (termes obligatoires, termes facultatifs, variantes) et comment la classer93//! (intention, langue, lieu).9495use crate::{fold, ParsedQuery};96use serde::{Deserialize, Serialize};97use unicode_normalization::UnicodeNormalization;9899#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]100#[serde(rename_all = "snake_case")]101pub enum Intent {102    Navigational,103    Informational,104    Commercial,105    Local,106    Scientific,107    News,108    Documentary,109    Technical,110}111112impl Intent {113    pub fn as_str(self) -> &'static str {114        match self {115            Intent::Navigational => "navigational",116            Intent::Informational => "informational",117            Intent::Commercial => "commercial",118            Intent::Local => "local",119            Intent::Scientific => "scientific",120            Intent::News => "news",121            Intent::Documentary => "documentary",122            Intent::Technical => "technical",123        }124    }125    pub const ALL: [Intent; 8] = [Intent::Navigational, Intent::Informational, Intent::Commercial, Intent::Local, Intent::Scientific, Intent::News, Intent::Documentary, Intent::Technical];126}127128/// Lieu nommé dans la requête : pays (code ISO 3166-1 alpha-2 en minuscules) et, s'il y a lieu, sous-région.129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]130pub struct Geo {131    pub country: String,132    pub sub: Option<String>,133    /// Le terme de la requête qui a désigné le lieu.134    pub term: String,135}136137/// Mots qui annoncent une recherche d'information, jamais le nom d'un site (« recette tourtière »).138const INFO_WORDS: &[&str] = &["recette", "recettes", "recipe", "recipes", "definition", "signification", "meaning", "histoire", "history", "exemple", "exemples", "example", "examples", "conseils", "tips", "idees", "ideas", "liste", "list", "avis", "review", "reviews", "symptomes", "symptoms", "traitement", "treatment", "paroles", "lyrics", "traduction", "translation", "synonyme", "synonymes", "conjugaison", "calcul", "calculer", "resume", "summary", "biographie", "biography", "horaire", "horaires"];139140#[derive(Debug, Clone, Serialize, Deserialize)]141pub struct Understanding {142    /// Langue de la requête : `fr`, `en`, `de`, `es`, `it`, `nl`… ou `und`.143    pub language: String,144    pub intent: Intent,145    /// Termes porteurs de sens (repliés), dans l'ordre : ils doivent figurer dans un document.146    pub content: Vec<String>,147    /// Mots vides et mots outils : ils comptent pour le score, jamais pour l'exclusion.148    pub optional: Vec<String>,149    /// Variantes d'un terme (pluriel/singulier, synonymes contrôlés) : un document qui contient la variante150    /// satisfait le terme, avec un poids moindre.151    pub expansions: Vec<(String, Vec<String>)>,152    pub geo: Option<Geo>,153    /// La requête demande du contenu récent.154    pub fresh: bool,155    /// La requête nomme explicitement un site ou une marque (« site officiel », « connexion », nom de domaine).156    pub nav_hint: bool,157}158159/// Normalisation d'entrée : NFKC, espaces insécables et caractères de contrôle ou de largeur nulle retirés,160/// apostrophes et guillemets typographiques ramenés à leur forme simple, espaces regroupés.161pub fn normalize_input(raw: &str) -> String {162    let mut out = String::with_capacity(raw.len());163    let mut last_space = true;164    for c in raw.nfkc() {165        let c = match c {166            '\u{2018}' | '\u{2019}' | '\u{02BC}' | '`' | '´' => '\'',167            '\u{00A0}' | '\u{202F}' | '\u{2009}' | '\u{2007}' | '\t' | '\n' | '\r' => ' ',168            '\u{200B}'..='\u{200F}' | '\u{2060}' | '\u{FEFF}' | '\u{00AD}' => continue,169            c if c.is_control() => continue,170            c => c,171        };172        if c == ' ' {173            if !last_space {174                out.push(' ');175            }176            last_space = true;177        } else {178            out.push(c);179            last_space = false;180        }181    }182    out.trim().to_string()183}184185const STOP_FR: &[&str] = &[186    "le", "la", "les", "l", "de", "du", "des", "d", "un", "une", "et", "en", "au", "aux", "a", "pour", "sur", "dans", "par", "avec", "sans", "ou", "que", "qui", "quoi", "est", "sont", "ce", "cette", "ces", "se", "sa", "son", "ses", "mon", "ma", "mes", "ton", "ta", "tes", "notre", "nos", "votre", "vos", "leur", "leurs", "il", "elle", "on", "nous", "vous", "ils", "elles", "je", "tu", "j", "y", "n", "ne", "pas", "plus", "c", "s", "qu", "m", "t", "chez", "vers", "entre", "comme", "si", "mais", "donc", "car", "ni", "tout", "tous", "toute", "toutes", "etre", "avoir", "fait", "faire", "peut", "dois", "doit", "faut",187];188const STOP_EN: &[&str] = &[189    "the", "of", "and", "an", "in", "for", "to", "on", "at", "by", "with", "from", "as", "is", "are", "was", "were", "be", "been", "it", "its", "this", "that", "these", "those", "or", "if", "but", "not", "no", "do", "does", "did", "can", "could", "should", "would", "will", "i", "you", "he", "she", "we", "they", "my", "your", "his", "her", "our", "their", "me", "us", "them", "am", "have", "has", "had", "so", "than", "then", "there", "here", "about", "into", "over", "s", "t",190];191/// Mots interrogatifs : facultatifs pour la recherche, mais ils signent une requête d'information.192const QUESTION_FR: &[&str] = &["comment", "pourquoi", "quand", "quel", "quelle", "quels", "quelles", "combien", "quoi"];193const QUESTION_EN: &[&str] = &["how", "what", "why", "when", "where", "which", "who", "whom", "whose"];194fn is_question(t: &str) -> bool {195    QUESTION_FR.contains(&t) || QUESTION_EN.contains(&t)196}197/// Mots en « s » qui ne sont pas des pluriels : ne jamais leur retirer la finale.198const NO_STRIP: &[&str] = &["news", "pays", "temps", "corps", "cours", "mars", "bus", "gas", "ios", "macos", "windows", "pandas", "kubernetes", "postgres", "canvas", "atlas", "texas", "series", "species", "jeans", "always", "sans", "dans", "plus", "tous", "vers", "alors", "moins", "parcs", "physics", "mathematics", "economics", "politics", "analytics", "status", "campus", "virus", "bonus", "focus", "jesus", "paris", "tennis", "travaux", "prix", "choix", "voix", "taux"];199200/// Marqueurs de langue hors mots vides : mots fréquents qui n'existent que dans une langue.201const HINT_FR: &[&str] = &["prix", "maison", "quebec", "montreal", "recette", "meteo", "emploi", "gratuit", "meilleur", "meilleure", "meilleurs", "avis", "ville", "universite", "gouvernement", "sante", "ecole", "cours", "calcul", "taux", "impot", "impots", "loi", "definition", "exemple", "exemples", "acheter", "vendre", "louer", "voiture", "travail", "francais", "francaise", "nouvelles", "actualites", "histoire", "logement", "hypotheque", "hypothecaire", "taxe", "taxes", "symptomes", "traitement", "horaire", "adresse", "telephone", "formulaire", "demande", "inscription", "admission", "programme", "programmes", "etudes", "recherche", "banque", "assurance", "retraite", "enfants", "famille", "restaurant", "hotel", "vol", "billet", "billets"];202const HINT_EN: &[&str] = &["price", "house", "home", "recipe", "weather", "job", "jobs", "free", "best", "review", "reviews", "city", "university", "government", "health", "school", "course", "rate", "rates", "tax", "taxes", "law", "definition", "example", "examples", "buy", "sell", "rent", "car", "work", "english", "news", "history", "housing", "mortgage", "symptoms", "treatment", "schedule", "address", "phone", "form", "application", "program", "programs", "study", "research", "bank", "insurance", "retirement", "children", "family", "flight", "ticket", "tickets", "tutorial", "guide", "meaning", "difference", "between", "near", "cheap", "online", "learn", "using", "error", "install"];203const STOP_DE: &[&str] = &["der", "die", "das", "und", "ist", "nicht", "ein", "eine", "mit", "fur", "auf", "von", "zu", "wie", "was", "ich", "den", "dem", "im", "bei", "nach", "oder", "auch", "wird"];204const STOP_ES: &[&str] = &["el", "los", "las", "del", "y", "es", "para", "con", "por", "como", "que", "una", "uno", "al", "lo", "su", "sus", "mas", "pero", "donde", "cuando"];205const STOP_IT: &[&str] = &["il", "lo", "gli", "di", "che", "per", "con", "una", "sono", "come", "della", "dei", "nel", "alla", "piu", "anche", "dove", "quando"];206const STOP_NL: &[&str] = &["het", "een", "van", "en", "is", "niet", "voor", "met", "op", "zijn", "dat", "naar", "ook", "bij", "wat", "hoe", "waar"];207208pub fn is_stopword(t: &str) -> bool {209    STOP_FR.contains(&t) || STOP_EN.contains(&t)210}211212/// Langue d'une requête courte. Les requêtes de un ou deux noms propres n'ont pas de langue : `und`.213pub fn detect_language(raw: &str, tokens: &[String]) -> String {214    let (mut fr, mut en, mut de, mut es, mut it, mut nl) = (0.0f32, 0.0f32, 0.0f32, 0.0f32, 0.0f32, 0.0f32);215    for t in tokens {216        let t = t.as_str();217        // Les mots communs à plusieurs langues (« a », « on », « est », « or »…) votent faiblement pour chacune.218        let (in_fr, in_en) = (STOP_FR.contains(&t) || QUESTION_FR.contains(&t), STOP_EN.contains(&t) || QUESTION_EN.contains(&t));219        match (in_fr, in_en) {220            (true, true) => {221                fr += 0.3;222                en += 0.3;223            }224            (true, false) => fr += 1.0,225            (false, true) => en += 1.0,226            _ => {}227        }228        if HINT_FR.contains(&t) {229            fr += 1.2;230        }231        if HINT_EN.contains(&t) {232            en += 1.2;233        }234        if STOP_DE.contains(&t) {235            de += 1.0;236        }237        if STOP_ES.contains(&t) {238            es += 1.0;239        }240        if STOP_IT.contains(&t) {241            it += 1.0;242        }243        if STOP_NL.contains(&t) {244            nl += 1.0;245        }246    }247    let lower = raw.to_lowercase();248    if lower.chars().any(|c| "éèêàùçôîûœâ".contains(c)) {249        fr += 1.0;250    }251    if lower.chars().any(|c| "ñ¿¡".contains(c)) {252        es += 1.5;253    }254    if lower.chars().any(|c| "äöüß".contains(c)) {255        de += 1.0;256    }257    // Élisions françaises : « l'université », « d'un ».258    if lower.contains("l'") || lower.contains("d'") || lower.contains("qu'") || lower.contains("j'") || lower.contains("n'") {259        fr += 0.8;260    }261    let mut scores = [("fr", fr), ("en", en), ("de", de), ("es", es), ("it", it), ("nl", nl)];262    scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));263    if scores[0].1 >= 0.8 && scores[0].1 >= scores[1].1 * 1.4 {264        return scores[0].0.to_string();265    }266    // Requêtes longues sans marqueur : détecteur statistique, seulement s'il est sûr de lui.267    if raw.chars().count() >= 24 && tokens.len() >= 4 {268        if let Some(info) = whatlang::detect(raw) {269            if info.is_reliable() {270                use whatlang::Lang::*;271                let c = match info.lang() {272                    Fra => "fr",273                    Eng => "en",274                    Deu => "de",275                    Spa => "es",276                    Ita => "it",277                    Nld => "nl",278                    Por => "pt",279                    _ => "",280                };281                if !c.is_empty() {282                    return c.to_string();283                }284            }285        }286    }287    "und".to_string()288}289290const NAV_WORDS: &[&str] = &["site", "officiel", "official", "website", "homepage", "accueil", "login", "connexion", "portail", "portal", "www", "signin"];291const TECH_WORDS: &[&str] = &[292    "python", "javascript", "typescript", "rust", "java", "golang", "kotlin", "swift", "php", "ruby", "sql", "postgres", "postgresql", "mysql", "sqlite", "mongodb", "redis", "docker", "kubernetes", "linux", "ubuntu", "debian", "bash", "shell", "git", "github", "gitlab", "api", "sdk", "cli", "regex", "json", "yaml", "xml", "html", "css", "react", "vue", "angular", "svelte", "node", "nodejs", "npm", "pip", "conda", "pandas", "numpy", "pytorch", "tensorflow", "django", "flask", "fastapi", "nginx", "apache", "ssh", "ssl", "tls", "http", "https", "tcp", "udp", "dns", "compiler", "compile", "debug", "error", "erreur", "exception", "stacktrace", "install", "installer", "installation", "config", "configuration", "configure", "documentation", "docs", "doc", "tutorial", "tutoriel", "tuto", "syntax", "syntaxe", "function", "fonction", "library", "bibliotheque", "framework", "algorithm", "algorithme", "terminal", "command", "commande", "script", "server", "serveur", "database", "macos", "windows", "android", "ios", "xcode", "vscode", "vim", "emacs", "latex", "markdown", "wasm", "webassembly", "llm", "kernel", "cron", "systemd", "ansible", "terraform", "aws", "azure", "gcp", "excel", "vba", "matlab", "stackoverflow", "segfault", "pointer", "async", "await", "thread", "mutex",293];294const COMMERCE_WORDS: &[&str] = &["acheter", "achat", "buy", "prix", "price", "prices", "pricing", "tarif", "tarifs", "cout", "couts", "cost", "cheap", "pas", "cher", "moins", "promo", "promotion", "rabais", "solde", "soldes", "deal", "deals", "discount", "coupon", "meilleur", "meilleure", "meilleurs", "meilleures", "best", "top", "comparatif", "comparaison", "comparer", "compare", "comparison", "vs", "versus", "avis", "review", "reviews", "test", "boutique", "magasin", "shop", "store", "vente", "vendre", "sale", "louer", "location", "rent", "rental", "devis", "soumission", "quote", "livraison", "shipping", "commander", "order", "abonnement", "subscription", "forfait", "forfaits"];295const LOCAL_WORDS: &[&str] = &["restaurant", "restaurants", "resto", "hotel", "hotels", "cafe", "bar", "pharmacie", "pharmacy", "clinique", "clinic", "hopital", "hospital", "dentiste", "dentist", "medecin", "doctor", "garage", "plombier", "plumber", "electricien", "electrician", "coiffeur", "salon", "epicerie", "grocery", "supermarche", "boulangerie", "bakery", "meteo", "weather", "horaire", "horaires", "hours", "adresse", "address", "pres", "proche", "near", "nearby", "itineraire", "directions", "quartier", "bibliotheque", "piscine", "parc", "park", "stationnement", "parking", "ecole", "garderie", "daycare", "notaire", "courtier", "agence", "demenagement", "moving", "taxi", "autobus", "bus", "metro", "train", "aeroport", "airport"];296const SCIENCE_WORDS: &[&str] = &["etude", "etudes", "study", "studies", "theoreme", "theorem", "hypothese", "hypothesis", "theorie", "theory", "equation", "equations", "preuve", "proof", "journal", "revue", "article", "paper", "papers", "publication", "publications", "recherche", "research", "meta-analyse", "meta-analysis", "essai", "clinique", "clinical", "trial", "molecule", "protein", "proteine", "genome", "gene", "genes", "adn", "dna", "rna", "arn", "quantum", "quantique", "relativite", "relativity", "thermodynamique", "thermodynamics", "entropie", "entropy", "neurone", "neuron", "neurons", "cellule", "cell", "cells", "enzyme", "isotope", "particule", "particle", "galaxie", "galaxy", "exoplanet", "exoplanete", "photosynthese", "photosynthesis", "econometrie", "econometrics", "regression", "bayesian", "bayesien", "stochastic", "stochastique", "statistique", "statistical", "epidemiologie", "epidemiology", "pathogen", "pathogene", "microbiome", "catalyst", "catalyseur", "polymer", "polymere", "tectonic", "tectonique", "doi", "arxiv", "pubmed", "peer-reviewed", "methodologie", "methodology", "empirical", "empirique", "model", "modele", "models"];297const DOC_WORDS: &[&str] = &["pdf", "rapport", "report", "reports", "rapports", "guide", "guides", "formulaire", "formulaires", "form", "forms", "loi", "lois", "reglement", "reglements", "regulation", "regulations", "law", "act", "code", "norme", "normes", "standard", "standards", "politique", "policy", "directive", "directives", "manuel", "manual", "memoire", "these", "thesis", "dissertation", "document", "documents", "gabarit", "template", "modele", "contrat", "contract", "bail", "lease", "declaration", "attestation", "certificat", "certificate", "plan", "budget", "bilan", "statistiques", "statistics", "donnees", "data", "dataset", "archives", "archive", "proces-verbal", "minutes", "whitepaper", "specification", "specifications", "rfc"];298const FRESH_WORDS: &[&str] = &["aujourd", "aujourdhui", "actualite", "actualites", "nouvelles", "news", "latest", "recent", "recents", "recente", "recentes", "today", "breaking", "dernier", "dernieres", "derniere", "derniers", "maintenant", "now", "live", "direct", "hier", "yesterday", "tonight", "semaine", "week", "manchettes", "headlines", "update", "updates"];299300/// Lieux reconnus : (terme replié, pays, sous-région). Volontairement court : les lieux qui changent le sens301/// d'une recherche pour le public du moteur (Québec, Canada, francophonie, grands pays).302const PLACES: &[(&str, &str, Option<&str>)] = &[303    ("quebec", "ca", Some("qc")), ("qc", "ca", Some("qc")), ("montreal", "ca", Some("qc")), ("mtl", "ca", Some("qc")), ("laval", "ca", Some("qc")), ("gatineau", "ca", Some("qc")), ("longueuil", "ca", Some("qc")), ("sherbrooke", "ca", Some("qc")), ("saguenay", "ca", Some("qc")), ("levis", "ca", Some("qc")), ("trois-rivieres", "ca", Some("qc")), ("terrebonne", "ca", Some("qc")), ("repentigny", "ca", Some("qc")), ("brossard", "ca", Some("qc")), ("drummondville", "ca", Some("qc")), ("granby", "ca", Some("qc")), ("rimouski", "ca", Some("qc")), ("outaouais", "ca", Some("qc")), ("estrie", "ca", Some("qc")), ("gaspesie", "ca", Some("qc")), ("laurentides", "ca", Some("qc")), ("lanaudiere", "ca", Some("qc")), ("monteregie", "ca", Some("qc")), ("mauricie", "ca", Some("qc")), ("abitibi", "ca", Some("qc")), ("charlevoix", "ca", Some("qc")), ("beauce", "ca", Some("qc")), ("quebecois", "ca", Some("qc")), ("quebecoise", "ca", Some("qc")), ("chicoutimi", "ca", Some("qc")), ("victoriaville", "ca", Some("qc")), ("shawinigan", "ca", Some("qc")), ("mirabel", "ca", Some("qc")), ("blainville", "ca", Some("qc")),304    ("canada", "ca", None), ("canadien", "ca", None), ("canadienne", "ca", None), ("canadian", "ca", None), ("ontario", "ca", Some("on")), ("toronto", "ca", Some("on")), ("ottawa", "ca", Some("on")), ("mississauga", "ca", Some("on")), ("hamilton", "ca", Some("on")), ("vancouver", "ca", Some("bc")), ("calgary", "ca", Some("ab")), ("edmonton", "ca", Some("ab")), ("alberta", "ca", Some("ab")), ("winnipeg", "ca", Some("mb")), ("manitoba", "ca", Some("mb")), ("saskatchewan", "ca", Some("sk")), ("halifax", "ca", Some("ns")), ("moncton", "ca", Some("nb")), ("nouveau-brunswick", "ca", Some("nb")), ("yukon", "ca", Some("yt")), ("nunavut", "ca", Some("nu")),305    ("france", "fr", None), ("paris", "fr", None), ("lyon", "fr", None), ("marseille", "fr", None), ("toulouse", "fr", None), ("bordeaux", "fr", None), ("nantes", "fr", None), ("lille", "fr", None), ("strasbourg", "fr", None), ("rennes", "fr", None), ("grenoble", "fr", None), ("bretagne", "fr", None), ("normandie", "fr", None),306    ("belgique", "be", None), ("belgium", "be", None), ("bruxelles", "be", None), ("brussels", "be", None), ("liege", "be", None), ("wallonie", "be", None),307    ("suisse", "ch", None), ("switzerland", "ch", None), ("geneve", "ch", None), ("geneva", "ch", None), ("lausanne", "ch", None), ("zurich", "ch", None),308    ("usa", "us", None), ("etats-unis", "us", None), ("america", "us", None), ("american", "us", None), ("california", "us", None), ("texas", "us", None), ("florida", "us", None), ("chicago", "us", None), ("boston", "us", None), ("seattle", "us", None),309    ("uk", "gb", None), ("england", "gb", None), ("london", "gb", None), ("londres", "gb", None), ("scotland", "gb", None), ("british", "gb", None), ("royaume-uni", "gb", None),310    ("germany", "de", None), ("allemagne", "de", None), ("deutschland", "de", None), ("berlin", "de", None), ("munich", "de", None),311    ("espagne", "es", None), ("spain", "es", None), ("madrid", "es", None), ("barcelone", "es", None), ("barcelona", "es", None),312    ("italie", "it", None), ("italy", "it", None), ("rome", "it", None), ("milan", "it", None),313    ("australia", "au", None), ("australie", "au", None), ("sydney", "au", None), ("melbourne", "au", None),314    ("maroc", "ma", None), ("morocco", "ma", None), ("senegal", "sn", None), ("dakar", "sn", None), ("tunisie", "tn", None), ("algerie", "dz", None), ("luxembourg", "lu", None),315];316317pub fn place(term: &str) -> Option<(&'static str, Option<&'static str>)> {318    PLACES.iter().find(|p| p.0 == term).map(|p| (p.1, p.2))319}320321/// Synonymes contrôlés (un seul jeton de chaque côté). Petit, relu, symétrique : une variante qui élargit trop322/// dégrade la précision plus qu'elle n'aide le rappel.323const SYNONYMS: &[(&str, &[&str])] = &[324    ("doc", &["documentation", "docs"]), ("docs", &["documentation", "doc"]), ("documentation", &["docs", "doc"]),325    ("tuto", &["tutoriel", "tutorial"]), ("tutoriel", &["tuto", "tutorial"]), ("tutorial", &["tutoriel", "guide"]),326    ("auto", &["voiture", "automobile"]), ("voiture", &["auto", "automobile", "vehicule"]), ("automobile", &["auto", "voiture"]),327    ("job", &["emploi"]), ("emploi", &["job", "emplois"]), ("boulot", &["emploi", "travail"]),328    ("hypotheque", &["hypothecaire", "pret"]), ("hypothecaire", &["hypotheque"]), ("mortgage", &["mortgages"]),329    ("maison", &["propriete", "residence"]), ("condo", &["copropriete", "condominium"]), ("appartement", &["logement"]), ("logement", &["appartement"]),330    ("prix", &["cout", "tarif"]), ("cout", &["prix", "tarif"]), ("tarif", &["prix", "cout"]),331    ("price", &["cost", "pricing"]), ("cost", &["price"]),332    ("meteo", &["previsions", "temps"]), ("weather", &["forecast"]),333    ("impot", &["fiscal", "fiscalite"]), ("tax", &["taxes", "taxation"]),334    ("velo", &["bicyclette", "cyclisme"]), ("bike", &["bicycle", "cycling"]),335    ("courriel", &["email", "mail"]), ("email", &["courriel", "mail"]),336    ("telecharger", &["telechargement", "download"]), ("download", &["downloads"]),337    ("cellulaire", &["mobile", "telephone"]), ("ordi", &["ordinateur"]), ("ordinateur", &["pc"]),338    ("js", &["javascript"]), ("ts", &["typescript"]), ("py", &["python"]), ("k8s", &["kubernetes"]), ("postgres", &["postgresql"]), ("postgresql", &["postgres"]),339    ("ia", &["intelligence", "ai"]), ("ai", &["ia"]), ("ml", &["machine"]),340    ("photo", &["photographie", "photos"]), ("film", &["cinema", "films"]), ("recette", &["recettes", "cuisine"]), ("recipe", &["recipes"]),341    ("covid", &["coronavirus"]), ("grippe", &["influenza"]), ("flu", &["influenza"]),342    ("uni", &["universite", "university"]), ("fac", &["faculte", "universite"]),343    ("gouv", &["gouvernement"]), ("gov", &["government"]),344    ("definition", &["signification"]), ("meaning", &["definition"]),345];346347/// Variantes morphologiques sûres d'un terme : pluriel et singulier réguliers du français et de l'anglais.348/// L'index n'a pas de racinisation ; sans cela « maisons » ne trouve pas « maison ».349fn morph_variants(t: &str, out: &mut Vec<String>) {350    let n = t.chars().count();351    if n < 4 || !t.chars().all(|c| c.is_alphabetic()) || NO_STRIP.contains(&t) {352        return;353    }354    let mut push = |s: String| {355        if s != t && s.chars().count() >= 3 && !out.contains(&s) {356            out.push(s);357        }358    };359    if let Some(stem) = t.strip_suffix("ies") {360        push(format!("{}y", stem));361    } else if let Some(stem) = t.strip_suffix("aux") {362        push(format!("{}al", stem));363        push(format!("{}au", stem));364    } else if let Some(stem) = t.strip_suffix("eaux") {365        push(format!("{}eau", stem));366    } else if let Some(stem) = t.strip_suffix("sses") {367        push(format!("{}ss", stem));368    } else if let Some(stem) = t.strip_suffix('s') {369        if !t.ends_with("ss") && !t.ends_with("us") && !t.ends_with("is") {370            push(stem.to_string());371        }372    } else {373        if t.ends_with("al") && n >= 5 {374            push(format!("{}aux", &t[..t.len() - 2]));375        }376        if t.ends_with('y') && n >= 5 {377            push(format!("{}ies", &t[..t.len() - 1]));378        }379        if !t.ends_with('x') && !t.ends_with('z') {380            push(format!("{}s", t));381        }382    }383}384385pub fn expansions_for(term: &str) -> Vec<String> {386    let mut v: Vec<String> = Vec::new();387    morph_variants(term, &mut v);388    if let Some((_, syn)) = SYNONYMS.iter().find(|s| s.0 == term) {389        for s in syn.iter() {390            if !v.iter().any(|x| x == s) {391                v.push(s.to_string());392            }393        }394    }395    v.truncate(4);396    v397}398399/// Analyse d'une requête déjà découpée. `raw` sert à la détection de langue (accents, élisions).400pub fn understand(raw: &str, q: &ParsedQuery) -> Understanding {401    let folded_raw = fold(raw);402    let all: Vec<String> = q.terms.clone();403    let phrase_terms: Vec<&String> = q.phrases.iter().flatten().collect();404    let mut tokens_for_lang: Vec<String> = all.clone();405    tokens_for_lang.extend(phrase_terms.iter().map(|s| s.to_string()));406    let language = q.lang.clone().unwrap_or_else(|| detect_language(raw, &tokens_for_lang));407408    // Mots vides : facultatifs, sauf si la requête n'est faite que de cela (« the who », « à la une »).409    let mut content: Vec<String> = Vec::new();410    let mut optional: Vec<String> = Vec::new();411    for t in &all {412        let stop = is_stopword(t) || (is_question(t) && all.len() > 1) || (t.chars().count() == 1 && !t.chars().all(|c| c.is_ascii_digit()) && all.len() > 1);413        if stop && !q.intitle.contains(t) {414            if !optional.contains(t) {415                optional.push(t.clone());416            }417        } else if !content.contains(t) {418            content.push(t.clone());419        }420    }421    if content.is_empty() && q.phrases.is_empty() {422        content = std::mem::take(&mut optional);423    }424425    let has = |list: &[&str]| content.iter().chain(optional.iter()).any(|t| list.contains(&t.as_str()));426    let count = |list: &[&str]| content.iter().filter(|t| list.contains(&t.as_str())).count();427    let question = all.iter().any(|t| is_question(t)) || raw.trim_end().ends_with('?');428    let fresh = has(FRESH_WORDS) || content.iter().any(|t| t.len() == 4 && t.starts_with("20") && t.chars().all(|c| c.is_ascii_digit()));429    let geo = content.iter().find_map(|t| place(t).map(|(c, s)| Geo { country: c.to_string(), sub: s.map(|x| x.to_string()), term: t.clone() }));430    let looks_like_host = raw.split_whitespace().any(|w| {431        let w = w.trim_start_matches("https://").trim_start_matches("http://").trim_start_matches("www.");432        w.contains('.') && w.split('.').count() >= 2 && w.split('.').last().map(|tld| (2..=6).contains(&tld.len()) && tld.chars().all(|c| c.is_ascii_alphabetic())).unwrap_or(false) && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '/')433    });434    let nav_hint = looks_like_host || (has(NAV_WORDS) && content.len() <= 5) || folded_raw.contains("site officiel") || folded_raw.contains("official site");435436    let tech = count(TECH_WORDS);437    let commerce = count(COMMERCE_WORDS);438    let local = count(LOCAL_WORDS);439    let science = count(SCIENCE_WORDS);440    let docs = count(DOC_WORDS);441    let near_me = folded_raw.contains("pres de moi") || folded_raw.contains("near me") || folded_raw.contains("pres de chez") || folded_raw.contains("a proximite");442    // Ordre de décision : les signaux explicites d'abord (navigation, actualité), puis le vocabulaire dominant.443    let intent = if nav_hint {444        Intent::Navigational445    } else if has(FRESH_WORDS) {446        Intent::News447    } else if tech >= 1 && tech >= commerce && tech >= science {448        Intent::Technical449    } else if near_me || (local >= 1 && (geo.is_some() || content.len() <= 3)) {450        Intent::Local451    } else if science >= 1 && science >= commerce && !question {452        Intent::Scientific453    } else if commerce >= 1 && commerce >= docs {454        Intent::Commercial455    } else if docs >= 1 {456        Intent::Documentary457    } else if science >= 1 {458        Intent::Scientific459    } else if !question && q.site.is_none() && !has(INFO_WORDS) && content.len() <= 2 && optional.len() <= 2 && geo.as_ref().map(|g| content.len() > 1 || g.term != content[0]).unwrap_or(true) && q.phrases.is_empty() {460        // Un ou deux mots porteurs sans autre indice : le plus souvent le nom d'un site, d'un organisme ou461        // d'une marque. Le classement confirme (ou non) avec les sites réellement présents dans l'index.462        Intent::Navigational463    } else {464        Intent::Informational465    };466467    let mut expansions: Vec<(String, Vec<String>)> = Vec::new();468    for t in &content {469        let v = expansions_for(t);470        if !v.is_empty() {471            expansions.push((t.clone(), v));472        }473    }474    Understanding { language, intent, content, optional, expansions, geo, fresh, nav_hint }475}476477#[cfg(test)]478mod tests {479    use super::*;480    use crate::parse;481    fn u(q: &str) -> Understanding {482        let n = normalize_input(q);483        understand(&n, &parse(&n).unwrap())484    }485    #[test]486    fn normalization() {487        assert_eq!(normalize_input("  l\u{2019}école\u{00A0}  de\u{200B}  Montréal "), "l'école de Montréal");488        assert_eq!(normalize_input("full width"), "full width");489    }490    #[test]491    fn stopwords_are_optional_not_dropped() {492        let x = u("how to change a tire");493        assert_eq!(x.content, vec!["change", "tire"]);494        assert!(x.optional.contains(&"how".to_string()) && x.optional.contains(&"to".to_string()));495        assert_eq!(x.language, "en");496        let x = u("the who");497        assert_eq!(x.content, vec!["the", "who"]);498    }499    #[test]500    fn languages() {501        assert_eq!(u("prix maison québec").language, "fr");502        assert_eq!(u("comment calculer la taxe de bienvenue").language, "fr");503        assert_eq!(u("best pizza recipe").language, "en");504        assert_eq!(u("mcgill").language, "und");505        assert_eq!(u("wie ist das wetter in berlin").language, "de");506    }507    #[test]508    fn intents() {509        assert_eq!(u("université laval").intent, Intent::Navigational);510        assert_eq!(u("site officiel revenu québec").intent, Intent::Navigational);511        assert_eq!(u("ulaval.ca").intent, Intent::Navigational);512        assert_eq!(u("python pandas documentation").intent, Intent::Technical);513        assert_eq!(u("prix maison québec").intent, Intent::Commercial);514        assert_eq!(u("restaurant italien montréal").intent, Intent::Local);515        assert_eq!(u("dernières nouvelles économie").intent, Intent::News);516        assert_eq!(u("black scholes model derivation proof").intent, Intent::Scientific);517        assert_eq!(u("formulaire demande de passeport").intent, Intent::Documentary);518        assert_eq!(u("comment fonctionne une pompe à chaleur").intent, Intent::Informational);519    }520    #[test]521    fn geo_and_expansions() {522        let x = u("prix maisons gatineau");523        assert_eq!(x.geo.as_ref().map(|g| (g.country.as_str(), g.sub.as_deref())), Some(("ca", Some("qc"))));524        assert!(x.expansions.iter().any(|e| e.0 == "maisons" && e.1.contains(&"maison".to_string())));525        assert!(expansions_for("journal").contains(&"journaux".to_string()));526        assert!(expansions_for("companies").contains(&"company".to_string()));527        assert!(expansions_for("class").is_empty() || !expansions_for("class").contains(&"clas".to_string()));528    }529}530
Files main
Menu

Theme