Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SPSearch9// File : crates/extractor/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-3015//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//! Extraction en mémoire : décodage, titre, description, langue, texte principal sans gabarit,89//! intertitres, date de publication fiable, canonical, directives, liens. Rien n'est écrit sur disque.9091use scraper::{ElementRef, Html, Node, Selector};92use spweb_policy::directives::{parse_date, Directives};93use url::Url;9495pub mod feeds;9697#[derive(Debug, Clone, Default)]98pub struct Page {99 pub title: String,100 pub description: String,101 pub lang: String,102 pub text: String,103 pub headings: String,104 pub canonical: Option<String>,105 pub directives: Directives,106 /// (href brut, nofollow)107 pub links: Vec<(String, bool)>,108 pub feeds: Vec<String>,109 pub published_at: Option<i64>,110 pub link_text_chars: usize,111 pub words: usize,112}113114/// Signature : le début du corps ressemble-t-il à du HTML ? (le Content-Type seul n'est pas fiable)115pub fn looks_like_html(bytes: &[u8]) -> bool {116 let head = &bytes[..bytes.len().min(2048)];117 if head.starts_with(b"%PDF") || head.starts_with(b"PK\x03\x04") || head.starts_with(&[0x1f, 0x8b]) || head.starts_with(b"\x89PNG") || head.starts_with(&[0xff, 0xd8, 0xff]) || head.starts_with(b"GIF8") {118 return false;119 }120 if head.iter().filter(|b| **b == 0).count() > 4 && !head.starts_with(&[0xff, 0xfe]) && !head.starts_with(&[0xfe, 0xff]) {121 return false;122 }123 let lower = String::from_utf8_lossy(head).to_ascii_lowercase();124 ["<!doctype html", "<html", "<head", "<body", "<title", "<meta", "<div", "<p>", "<h1"].iter().any(|m| lower.contains(m))125}126127/// Décode le corps selon le charset de l'en-tête, sinon BOM, sinon `<meta charset>`, sinon UTF-8 (avec repli windows-1252).128pub fn decode(bytes: &[u8], content_type: Option<&str>) -> String {129 let from_label = |l: &str| encoding_rs::Encoding::for_label(l.trim().trim_matches(|c| c == '"' || c == '\'').as_bytes());130 let mut enc = content_type131 .and_then(|ct| ct.to_ascii_lowercase().split(';').find_map(|p| p.trim().strip_prefix("charset=").map(|s| s.to_string())))132 .and_then(|l| from_label(&l));133 if let Some((e, _)) = encoding_rs::Encoding::for_bom(bytes) {134 enc = Some(e);135 }136 if enc.is_none() {137 let head = String::from_utf8_lossy(&bytes[..bytes.len().min(2048)]).to_ascii_lowercase();138 if let Some(i) = head.find("charset=") {139 let label: String = head[i + 8..].trim_start_matches(['"', '\'']).chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect();140 enc = from_label(&label);141 }142 }143 match enc {144 Some(e) => e.decode(bytes).0.into_owned(),145 None => match std::str::from_utf8(bytes) {146 Ok(s) => s.to_string(),147 Err(_) => {148 let lossy = String::from_utf8_lossy(bytes);149 let bad = lossy.chars().filter(|c| *c == '\u{fffd}').count();150 if bad * 200 > lossy.len() { encoding_rs::WINDOWS_1252.decode(bytes).0.into_owned() } else { lossy.into_owned() }151 }152 },153 }154}155156const SKIP_TAGS: &[&str] = &[157 "script", "style", "noscript", "template", "nav", "header", "footer", "aside", "form", "svg", "iframe", "button", "select", "option", "canvas", "object", "embed",158 "figure", "dialog", "menu", "video", "audio", "map", "input", "textarea", "label",159];160const BLOCK_TAGS: &[&str] = &["p", "div", "br", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "td", "th", "table", "section", "article", "blockquote", "pre", "dd", "dt", "hr", "main"];161const BOILER_WORDS: &[&str] = &[162 "nav", "menu", "sidebar", "footer", "cookie", "consent", "banner", "advert", "promo", "share", "social", "comment", "breadcrumb", "related", "newsletter", "popup",163 "modal", "subscribe", "widget", "masthead", "skip-link", "pagination", "toolbar", "sponsor",164];165166fn is_boilerplate(el: &scraper::node::Element) -> bool {167 if SKIP_TAGS.contains(&el.name()) {168 return true;169 }170 if el.attr("hidden").is_some() || el.attr("aria-hidden") == Some("true") {171 return true;172 }173 if matches!(el.attr("role"), Some("navigation" | "banner" | "contentinfo" | "complementary" | "search" | "dialog")) {174 return true;175 }176 let mut label = String::new();177 if let Some(c) = el.attr("class") {178 label.push_str(c);179 }180 if let Some(i) = el.attr("id") {181 label.push(' ');182 label.push_str(i);183 }184 if label.is_empty() || label.len() > 200 {185 return false;186 }187 let l = label.to_ascii_lowercase();188 // jetons de classe entiers ou préfixes/suffixes séparés par - ou _189 l.split(|c: char| c.is_whitespace()).any(|tok| tok.split(['-', '_']).any(|part| BOILER_WORDS.contains(&part)) || BOILER_WORDS.contains(&tok))190}191192struct Collected {193 text: String,194 headings: String,195 link_chars: usize,196}197198/// Parcours itératif (pas de récursion : résiste aux arbres très profonds).199fn collect_text(root: ElementRef, max_chars: usize) -> Collected {200 let mut out = Collected { text: String::new(), headings: String::new(), link_chars: 0 };201 let mut skip_depth = 0usize;202 let mut heading_depth = 0usize;203 let mut link_depth = 0usize;204 for edge in root.traverse() {205 match edge {206 ego_edge::Open(node) => match node.value() {207 Node::Element(el) => {208 if skip_depth > 0 || (node.id() != root.id() && is_boilerplate(el)) {209 skip_depth += 1;210 continue;211 }212 let n = el.name();213 if BLOCK_TAGS.contains(&n) && !out.text.ends_with(' ') && !out.text.is_empty() {214 out.text.push(' ');215 }216 if matches!(n, "h1" | "h2" | "h3") {217 heading_depth += 1;218 if !out.headings.is_empty() {219 out.headings.push_str(" · ");220 }221 }222 if n == "a" {223 link_depth += 1;224 }225 }226 Node::Text(t) => {227 if skip_depth == 0 && out.text.len() < max_chars * 4 {228 out.text.push_str(t);229 if heading_depth > 0 && out.headings.len() < 600 {230 out.headings.push_str(t);231 }232 if link_depth > 0 {233 out.link_chars += t.trim().chars().count();234 }235 }236 }237 _ => {}238 },239 ego_edge::Close(node) => {240 if let Node::Element(el) = node.value() {241 if skip_depth > 0 {242 skip_depth -= 1;243 continue;244 }245 let n = el.name();246 if matches!(n, "h1" | "h2" | "h3") && heading_depth > 0 {247 heading_depth -= 1;248 }249 if n == "a" && link_depth > 0 {250 link_depth -= 1;251 }252 if BLOCK_TAGS.contains(&n) && !out.text.ends_with(' ') {253 out.text.push(' ');254 }255 }256 }257 }258 }259 out.text = spweb_common::squash_ws(&out.text);260 if out.text.chars().count() > max_chars {261 out.text = out.text.chars().take(max_chars).collect();262 }263 out.headings = spweb_common::squash_ws(&out.headings);264 out265}266267use ego_tree::iter::Edge as ego_edge;268269fn sel(s: &str) -> Selector {270 Selector::parse(s).expect("sélecteur statique")271}272273fn meta(doc: &Html, selector: &str) -> Option<String> {274 doc.select(&sel(selector)).filter_map(|e| e.value().attr("content")).map(spweb_common::squash_ws).find(|s| !s.is_empty())275}276277fn iso_lang(code: &str) -> Option<String> {278 let c = code.trim().to_ascii_lowercase();279 let two: String = c.split(['-', '_']).next().unwrap_or("").to_string();280 if (2..=3).contains(&two.len()) && two.chars().all(|ch| ch.is_ascii_lowercase()) {281 Some(two)282 } else {283 None284 }285}286287fn detect_lang(text: &str) -> Option<String> {288 let sample: String = text.chars().take(2000).collect();289 if sample.chars().count() < 60 {290 return None;291 }292 let info = whatlang::detect(&sample)?;293 if !info.is_reliable() && info.confidence() < 0.5 {294 return None;295 }296 use whatlang::Lang::*;297 let c = match info.lang() {298 Fra => "fr", Eng => "en", Spa => "es", Deu => "de", Ita => "it", Por => "pt", Nld => "nl", Rus => "ru", Jpn => "ja", Cmn => "zh", Kor => "ko",299 Ara => "ar", Hin => "hi", Tur => "tr", Pol => "pl", Swe => "sv", Dan => "da", Fin => "fi", Nob => "no", Ces => "cs", Ell => "el", Heb => "he",300 Ukr => "uk", Ron => "ro", Hun => "hu", Vie => "vi", Ind => "id", Tha => "th", Cat => "ca", Bul => "bg", Hrv => "hr", Srp => "sr", Slk => "sk",301 Lit => "lt", Lav => "lv", Est => "et", Pes => "fa", Ben => "bn", Tam => "ta",302 _ => return None,303 };304 Some(c.to_string())305}306307pub fn extract(html: &str, base: &Url, max_chars: usize, now: i64) -> Page {308 let doc = Html::parse_document(html);309 let mut page = Page::default();310311 // Titre : <title>, sinon og:title, sinon premier h1312 page.title = doc.select(&sel("head > title, title")).next().map(|t| spweb_common::squash_ws(&t.text().collect::<String>())).unwrap_or_default();313 if page.title.is_empty() {314 page.title = meta(&doc, r#"meta[property="og:title"]"#).unwrap_or_default();315 }316 if page.title.is_empty() {317 page.title = doc.select(&sel("h1")).next().map(|t| spweb_common::squash_ws(&t.text().collect::<String>())).unwrap_or_default();318 }319 page.description = meta(&doc, r#"meta[name="description" i]"#).or_else(|| meta(&doc, r#"meta[property="og:description"]"#)).unwrap_or_default();320321 // Directives : meta robots + meta spbot (la plus restrictive)322 for m in doc.select(&sel(r#"meta[name="robots" i], meta[name="spbot" i], meta[name="spboucherbot" i]"#)) {323 if let Some(c) = m.value().attr("content") {324 page.directives.merge(&Directives::parse_content(c));325 }326 }327328 page.canonical = doc329 .select(&sel(r#"link[rel~="canonical" i]"#))330 .filter_map(|l| l.value().attr("href"))331 .find(|h| !h.trim().is_empty())332 .map(|s| s.trim().to_string());333334 for l in doc.select(&sel(r#"link[rel~="alternate" i]"#)) {335 let ty = l.value().attr("type").unwrap_or("").to_ascii_lowercase();336 if (ty.contains("rss") || ty.contains("atom")) && page.feeds.len() < 4 {337 if let Some(h) = l.value().attr("href") {338 page.feeds.push(h.trim().to_string());339 }340 }341 }342343 // Zone principale344 let mains: Vec<ElementRef> = doc.select(&sel(r#"main, [role="main"]"#)).collect();345 let articles: Vec<ElementRef> = doc.select(&sel("article")).collect();346 let body = doc.select(&sel("body")).next();347 let root = if mains.len() == 1 {348 Some(mains[0])349 } else if articles.len() == 1 {350 Some(articles[0])351 } else {352 body353 };354 if let Some(r) = root {355 let mut c = collect_text(r, max_chars);356 // Zone principale presque vide (gabarit mal balisé) : repli sur le corps entier.357 if c.text.chars().count() < 200 {358 if let Some(b) = body {359 if b.id() != r.id() {360 let alt = collect_text(b, max_chars);361 if alt.text.len() > c.text.len() {362 c = alt;363 }364 }365 }366 }367 page.words = c.text.split_whitespace().count();368 page.link_text_chars = c.link_chars;369 page.text = c.text;370 page.headings = spweb_common::truncate_chars(&c.headings, 400);371 }372373 // Langue : attribut déclaré, vérifié par détection quand le texte suffit374 let declared = doc.select(&sel("html")).next().and_then(|h| h.value().attr("lang")).and_then(iso_lang);375 let detected = detect_lang(&page.text);376 page.lang = detected.or(declared).unwrap_or_else(|| "und".to_string());377378 // Date de publication : seulement si déclarée par la page et plausible379 let mut cands: Vec<String> = Vec::new();380 for s in [381 r#"meta[property="article:published_time"]"#,382 r#"meta[itemprop="datePublished"]"#,383 r#"meta[name="date" i]"#,384 r#"meta[name="dc.date" i]"#,385 r#"meta[name="dcterms.created" i]"#,386 r#"meta[name="pubdate" i]"#,387 r#"meta[name="publish-date" i]"#,388 r#"meta[name="dc.date.issued" i]"#,389 ] {390 if let Some(v) = meta(&doc, s) {391 cands.push(v);392 }393 }394 if let Some(t) = doc.select(&sel("time[datetime][pubdate], article time[datetime], time[itemprop=\"datePublished\"]")).next() {395 if let Some(v) = t.value().attr("datetime") {396 cands.push(v.to_string());397 }398 }399 if let Some(i) = html.find("\"datePublished\"") {400 let rest = &html[i + 15..(i + 80).min(html.len())];401 if let Some(a) = rest.find('"') {402 if let Some(b) = rest[a + 1..].find('"') {403 cands.push(rest[a + 1..a + 1 + b].to_string());404 }405 }406 }407 page.published_at = cands.iter().filter_map(|c| parse_date(c)).find(|t| *t <= now + 86_400);408409 // Liens410 let page_nofollow = page.directives.nofollow;411 if !page_nofollow {412 for a in doc.select(&sel("a[href]")) {413 if page.links.len() >= 2000 {414 break;415 }416 let href = a.value().attr("href").unwrap_or("").trim();417 if href.is_empty() || href.starts_with('#') || href.len() > 1024 {418 continue;419 }420 let lower = href.get(..11.min(href.len())).unwrap_or("").to_ascii_lowercase();421 if lower.starts_with("javascript:") || lower.starts_with("mailto:") || lower.starts_with("tel:") || lower.starts_with("data:") {422 continue;423 }424 let rel = a.value().attr("rel").unwrap_or("").to_ascii_lowercase();425 let nf = rel.split_whitespace().any(|r| matches!(r, "nofollow" | "ugc" | "sponsored"));426 page.links.push((href.to_string(), nf));427 }428 }429 let _ = base;430 page431}432433/// Extrait autorisé : description de la page si présente, sinon début du texte principal ; borné par les directives.434pub fn snippet(page: &Page, system_max: usize) -> String {435 let budget = page.directives.snippet_budget(system_max);436 if budget == 0 {437 return String::new();438 }439 let src = if page.description.chars().count() >= 50 { &page.description } else { &page.text };440 spweb_common::truncate_chars(src, budget)441}442443/// Qualité éditoriale estimée dans [0, 1] à partir de signaux mesurables.444pub fn quality(page: &Page, depth: u32) -> f32 {445 let mut q: f32 = 0.0;446 let w = page.words as f32;447 // volume de texte utile (saturation vers 600 mots)448 q += 0.40 * (w / 600.0).min(1.0);449 if (10..=110).contains(&page.title.chars().count()) {450 q += 0.15;451 }452 if page.description.chars().count() >= 50 {453 q += 0.08;454 }455 if !page.headings.is_empty() {456 q += 0.07;457 }458 if page.lang != "und" {459 q += 0.10;460 }461 if page.published_at.is_some() {462 q += 0.05;463 }464 // proportion de texte qui n'est pas du texte de lien (pages portail, fermes de liens)465 let total = page.text.chars().count().max(1) as f32;466 let link_ratio = (page.link_text_chars as f32 / total).min(1.0);467 q += 0.15 * (1.0 - link_ratio);468 q -= 0.3 * (link_ratio - 0.6).max(0.0);469 // bourrage de mots-clés : un même terme long domine le texte470 if page.words >= 80 {471 let mut freq: std::collections::HashMap<&str, u32> = std::collections::HashMap::new();472 let mut n = 0u32;473 for t in page.text.split_whitespace().filter(|t| t.chars().count() >= 5) {474 *freq.entry(t).or_insert(0) += 1;475 n += 1;476 }477 let top = freq.values().copied().max().unwrap_or(0) as f32;478 if n > 0 && top / n as f32 > 0.12 {479 q -= 0.30;480 }481 }482 q -= 0.02 * (depth.min(8) as f32);483 q.clamp(0.0, 1.0)484}485486/// Texte normalisé pour l'empreinte (minuscules, blancs écrasés) : sert au hachage, jamais stocké.487pub fn fingerprint_text(page: &Page) -> String {488 let mut s = String::with_capacity(page.title.len() + page.text.len() + 1);489 s.push_str(&page.title.to_lowercase());490 s.push('\n');491 s.push_str(&page.text.to_lowercase());492 s493}494495#[cfg(test)]496mod tests {497 use super::*;498 fn base() -> Url {499 Url::parse("https://example.org/a/b").unwrap()500 }501 const DOC: &str = r##"<!doctype html><html lang="fr-CA"><head><title> Le conseil adopte le budget </title>502<meta name="description" content="Le conseil municipal a adopté le budget annuel après un long débat public, sans hausse de taxes.">503<meta name="robots" content="max-snippet:40"><link rel="canonical" href="/a/b?x=1">504<link rel="alternate" type="application/rss+xml" href="/feed.xml">505<meta property="article:published_time" content="2026-11-20T10:00:00-05:00">506<script>var secret = "NE PAS INDEXER";</script><style>.x{}</style></head>507<body><nav><a href="/menu">Menu principal du site</a></nav><div class="cookie-banner">Nous utilisons des témoins</div>508<main><h1>Le conseil adopte le budget</h1><p>Le conseil municipal de la ville a adopté hier soir le budget annuel.509Les élus ont débattu pendant plusieurs heures des priorités de la prochaine année, notamment le transport collectif,510l'entretien des rues et la bibliothèque du quartier. La mairesse a souligné que les taxes ne seront pas augmentées.</p>511<h2>Réactions</h2><p>Plusieurs citoyens ont salué la décision. <a href="/suite">Lire la suite</a>512<a href="https://autre.example/x" rel="nofollow">Commandité</a> <a href="javascript:alert(1)">x</a><a href="#top">haut</a></p>513<form><input name="q"><button>Chercher</button></form></main>514<footer>Pied de page © tous droits réservés</footer></body></html>"##;515 #[test]516 fn extracts_main_content_only() {517 let p = extract(DOC, &base(), 24_000, 1_800_000_000);518 assert_eq!(p.title, "Le conseil adopte le budget");519 assert!(p.text.contains("transport collectif"));520 for banned in ["NE PAS INDEXER", "Menu principal", "témoins", "Pied de page", "Chercher"] {521 assert!(!p.text.contains(banned), "{} dans le texte", banned);522 }523 assert_eq!(p.lang, "fr");524 assert_eq!(p.canonical.as_deref(), Some("/a/b?x=1"));525 assert_eq!(p.feeds, vec!["/feed.xml"]);526 assert!(p.headings.contains("Réactions"));527 assert_eq!(p.published_at, Some(parse_date("2026-11-20T15:00:00Z").unwrap()));528 let hrefs: Vec<&str> = p.links.iter().map(|l| l.0.as_str()).collect();529 assert!(hrefs.contains(&"/suite") && hrefs.contains(&"/menu"));530 assert!(!hrefs.iter().any(|h| h.starts_with("javascript")) && !hrefs.contains(&"#top"));531 assert!(p.links.iter().any(|l| l.0.contains("autre.example") && l.1));532 assert_eq!(snippet(&p, 240).chars().count(), 40);533 assert!(quality(&p, 1) > 0.3);534 }535 #[test]536 fn directives_and_future_date() {537 let html = r#"<html><head><meta name="ROBOTS" content="noindex, nofollow"><meta name="spbot" content="nosnippet">538 <meta property="article:published_time" content="2099-01-01"></head><body><p>x</p><a href="/a">a</a></body></html>"#;539 let p = extract(html, &base(), 1000, 1_800_000_000);540 assert!(p.directives.noindex && p.directives.nofollow && p.directives.nosnippet);541 assert!(p.links.is_empty());542 assert_eq!(p.published_at, None);543 assert_eq!(snippet(&p, 240), "");544 }545 #[test]546 fn malformed_and_deep_html_do_not_panic() {547 let p = extract("<html><body><p>ok<div><span>texte <b>non fermé<table><tr><td>cellule", &base(), 1000, 0);548 assert!(p.text.contains("cellule"));549 let deep = format!("<html><body>{}fond{}</body></html>", "<div>".repeat(20_000), "</div>".repeat(20_000));550 let p = extract(&deep, &base(), 1000, 0);551 assert!(p.text.contains("fond") || p.text.is_empty());552 let p = extract("", &base(), 1000, 0);553 assert!(p.title.is_empty() && p.text.is_empty());554 }555 #[test]556 fn decoding() {557 assert_eq!(decode(b"caf\xe9", Some("text/html; charset=ISO-8859-1")), "café");558 assert_eq!(decode("café".as_bytes(), Some("text/html")), "café");559 assert_eq!(decode(b"<meta charset=\"windows-1252\">caf\xe9", None), "<meta charset=\"windows-1252\">café");560 assert_eq!(decode(b"\xef\xbb\xbfabc", Some("text/html; charset=latin1")), "abc");561 }562 #[test]563 fn signatures() {564 assert!(looks_like_html(b" <!DOCTYPE html><html>"));565 assert!(!looks_like_html(b"%PDF-1.7 ..."));566 assert!(!looks_like_html(b"PK\x03\x04zip"));567 assert!(!looks_like_html(b"{\"json\": true}"));568 }569 #[test]570 fn stuffing_lowers_quality() {571 let stuffed = format!("<html><head><title>Casino bonus gratuit en ligne</title></head><body><main><p>{}</p></main></body></html>", "casino bonus gratuit jouer ".repeat(200));572 let p = extract(&stuffed, &base(), 24_000, 0);573 let honest = extract(DOC, &base(), 24_000, 1_800_000_000);574 assert!(quality(&p, 1) < quality(&honest, 1));575 }576}577