Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-geo/src/norm.rs10// Module : server11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687//! Normalisation des noms (rues, lieux, requêtes) — UNIQUE implémentation, utilisée par le service88//! et par le pipeline d'import (`km-geo norm`), pour que l'index et la requête parlent la même langue.89//!90//! Règles : minuscules, sans accents, ponctuation → espaces ; abréviations développées91//! (`av` → avenue, `boul` → boulevard, `ch` → chemin, `st`/`ste` → saint/sainte…) ; ordinaux réduits92//! au nombre (`1re`, `2e` → 1, 2) ; articles et particules retirés (`de`, `du`, `des`, `la`, `le`, `l'`, `d'`).9394/// Génériques de voie (formes normalisées).95pub const GENERICS: &[&str] = &[96 "rue", "avenue", "boulevard", "chemin", "route", "rang", "montee", "place", "terrasse", "promenade",97 "impasse", "croissant", "autoroute", "cote", "allee", "carre", "cercle", "cours", "cour", "ruelle",98 "sentier", "passage", "square", "voie", "quai", "desserte", "concession", "jardin", "parc", "circuit",99 "carrefour", "crete", "ile", "drive", "lane", "trail", "court", "crescent", "terrace", "circle",100];101102const STOP: &[&str] = &["de", "du", "des", "la", "le", "les", "l", "d", "the", "of", "au", "aux", "et", "and"];103104fn fold_char(c: char, out: &mut String) {105 match c {106 'a'..='z' | '0'..='9' => out.push(c),107 'A'..='Z' => out.push(c.to_ascii_lowercase()),108 'à' | 'â' | 'ä' | 'á' | 'ã' | 'å' | 'À' | 'Â' | 'Ä' | 'Á' | 'Ã' | 'Å' => out.push('a'),109 'ç' | 'Ç' => out.push('c'),110 'é' | 'è' | 'ê' | 'ë' | 'É' | 'È' | 'Ê' | 'Ë' => out.push('e'),111 'î' | 'ï' | 'í' | 'ì' | 'Î' | 'Ï' | 'Í' | 'Ì' => out.push('i'),112 'ñ' | 'Ñ' => out.push('n'),113 'ô' | 'ö' | 'ó' | 'ò' | 'õ' | 'Ô' | 'Ö' | 'Ó' | 'Ò' | 'Õ' => out.push('o'),114 'ù' | 'û' | 'ü' | 'ú' | 'Ù' | 'Û' | 'Ü' | 'Ú' => out.push('u'),115 'ÿ' | 'ý' | 'Ÿ' | 'Ý' => out.push('y'),116 'œ' | 'Œ' => out.push_str("oe"),117 'æ' | 'Æ' => out.push_str("ae"),118 _ => out.push(' '),119 }120}121122/// Minuscules ASCII, sans accents, tout le reste en espaces.123pub fn fold(s: &str) -> String {124 let mut out = String::with_capacity(s.len());125 for c in s.chars() {126 fold_char(c, &mut out);127 }128 out129}130131fn ordinal(tok: &str) -> Option<&str> {132 let digits = tok.trim_end_matches(|c: char| c.is_ascii_lowercase());133 if digits.is_empty() || digits.len() == tok.len() || !digits.bytes().all(|b| b.is_ascii_digit()) {134 return None;135 }136 match &tok[digits.len()..] {137 "e" | "er" | "re" | "ere" | "eme" | "ieme" | "ie" | "nd" | "rd" | "th" | "st" | "nde" => Some(digits),138 _ => None,139 }140}141142fn expand(tok: &str) -> &str {143 match tok {144 "av" | "ave" | "aven" => "avenue",145 "boul" | "blvd" | "bd" | "bl" | "boulv" | "bld" => "boulevard",146 "ch" | "chem" | "road" | "rd" => "chemin",147 "rte" | "rt" => "route",148 "rg" => "rang",149 "mtee" | "mte" => "montee",150 "pl" => "place",151 "tsse" | "terr" => "terrasse",152 "prom" | "prmnde" => "promenade",153 "imp" => "impasse",154 "crois" | "cr" | "cres" => "croissant",155 "aut" | "autor" | "hwy" => "autoroute",156 "car" => "carre",157 "rle" => "ruelle",158 "sent" => "sentier",159 "passge" | "pass" => "passage",160 "sq" => "square",161 "desste" => "desserte",162 "conc" => "concession",163 "street" | "str" => "rue",164 "dr" => "drive",165 "crt" | "ct" => "court",166 "cir" => "circle",167 "ste" => "sainte",168 "sts" => "saints",169 "mt" => "mont",170 "nd" => "notre dame",171 "ndg" => "notre dame grace",172 "mtl" => "montreal",173 "qc" => "quebec",174 "east" => "est",175 "west" => "ouest",176 "north" => "nord",177 "south" => "sud",178 "1er" | "premier" | "premiere" => "1",179 other => other,180 }181}182183fn is_dir(tok: &str) -> bool {184 matches!(tok, "e" | "o" | "w" | "n" | "s" | "est" | "ouest" | "nord" | "sud" | "east" | "west" | "north" | "south")185}186187/// Jetons normalisés d'un nom ou d'une requête.188pub fn tokens(s: &str) -> Vec<String> {189 let folded = fold(s);190 let raw: Vec<&str> = folded.split_ascii_whitespace().collect();191 let n = raw.len();192 let mut out: Vec<String> = Vec::with_capacity(n);193 for (i, tok) in raw.iter().enumerate() {194 let last = i + 1 == n;195 let rest_is_dir = i + 2 == n && is_dir(raw[n - 1]);196 let mapped: &str = if let Some(d) = ordinal(tok) {197 d198 } else if *tok == "st" {199 // « Peel St » (générique anglais en fin de nom) contre « St-Denis » (saint).200 if i > 0 && (last || rest_is_dir) { "rue" } else { "saint" }201 } else if last && i > 0 {202 match *tok {203 "e" => "est",204 "o" | "w" => "ouest",205 "n" => "nord",206 "s" => "sud",207 t => expand(t),208 }209 } else {210 expand(tok)211 };212 if STOP.contains(&mapped) {213 continue;214 }215 for part in mapped.split(' ') {216 out.push(part.to_string());217 }218 }219 if out.is_empty() {220 // Nom fait uniquement de particules (« La », « L'A ») : on garde les jetons bruts.221 out = raw.iter().map(|t| t.to_string()).collect();222 }223 out224}225226/// Forme normalisée complète (jetons séparés par une espace).227pub fn norm(s: &str) -> String {228 tokens(s).join(" ")229}230231/// Forme sans le générique de voie : « rue saint denis » → « saint denis », « 1 avenue » → « 1 ».232pub fn core_of(tokens: &[String]) -> String {233 if tokens.len() < 2 {234 return tokens.join(" ");235 }236 let mut a = 0;237 let mut b = tokens.len();238 if GENERICS.contains(&tokens[0].as_str()) {239 a = 1;240 } else if tokens[0].bytes().all(|c| c.is_ascii_digit()) && GENERICS.contains(&tokens[1].as_str()) {241 // « 1 avenue », « 5 rang est » : le spécifique est le nombre.242 return std::iter::once(tokens[0].as_str())243 .chain(tokens[2..].iter().map(|s| s.as_str()))244 .collect::<Vec<_>>()245 .join(" ");246 } else if GENERICS.contains(&tokens[b - 1].as_str()) {247 b -= 1;248 }249 tokens[a..b].join(" ")250}251252pub fn is_generic(tok: &str) -> bool {253 GENERICS.contains(&tok)254}255256#[cfg(test)]257mod tests {258 use super::*;259260 #[test]261 fn accents_and_punctuation() {262 assert_eq!(norm("Rue Saint-Denis"), "rue saint denis");263 assert_eq!(norm("Boulevard René-Lévesque Ouest"), "boulevard rene levesque ouest");264 assert_eq!(norm("Chemin de la Côte-Sainte-Catherine"), "chemin cote sainte catherine");265 assert_eq!(norm("Avenue de l'Hôtel-de-Ville"), "avenue hotel ville");266 assert_eq!(norm("rue d'Youville"), "rue youville");267 assert_eq!(norm("L'Île-Bizard–Sainte-Geneviève"), "ile bizard sainte genevieve");268 assert_eq!(norm("Cœur-de-l'Île"), "coeur ile");269 }270271 #[test]272 fn abbreviations() {273 assert_eq!(norm("boul st-laurent"), "boulevard saint laurent");274 assert_eq!(norm("av. du Parc"), "avenue parc");275 assert_eq!(norm("ch ste-foy"), "chemin sainte foy");276 assert_eq!(norm("BOUL. RENE LEVESQUE O"), "boulevard rene levesque ouest");277 assert_eq!(norm("rte 132"), "route 132");278 assert_eq!(norm("Peel St"), "peel rue");279 assert_eq!(norm("Sherbrooke St W"), "sherbrooke rue ouest");280 assert_eq!(norm("St-Jean-sur-Richelieu"), "saint jean sur richelieu");281 assert_eq!(norm("st hubert"), "saint hubert");282 assert_eq!(norm("Queen Mary Road"), "queen mary chemin");283 assert_eq!(norm("mtee masson"), "montee masson");284 }285286 #[test]287 fn ordinals() {288 assert_eq!(norm("1re Avenue"), "1 avenue");289 assert_eq!(norm("3e Rang Ouest"), "3 rang ouest");290 assert_eq!(norm("42ième rue"), "42 rue");291 assert_eq!(norm("1er Rang"), "1 rang");292 assert_eq!(norm("Rang 4"), "rang 4");293 assert_eq!(norm("1234a"), "1234a");294 }295296 #[test]297 fn stopwords_never_empty_the_name() {298 assert_eq!(norm("La"), "la");299 assert_eq!(norm(" "), "");300 assert_eq!(norm("La Tuque"), "tuque");301 }302303 #[test]304 fn core() {305 let c = |s: &str| core_of(&tokens(s));306 assert_eq!(c("Rue Saint-Denis"), "saint denis");307 assert_eq!(c("1re Avenue"), "1");308 assert_eq!(c("5e Rang Est"), "5 est");309 assert_eq!(c("Peel Street"), "peel");310 assert_eq!(c("Rue"), "rue");311 assert_eq!(c("Montréal"), "montreal");312 assert_eq!(c("Chemin du Roy"), "roy");313 }314315 #[test]316 fn idempotent() {317 for s in ["Boul. St-Joseph E", "1re Avenue", "Chemin de la Côte-des-Neiges", "rue de l'Église"] {318 let n = norm(s);319 assert_eq!(norm(&n), n, "{s}");320 }321 }322}323