Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/normalize.py10# Description : Fonctions de normalisation partagées par tous les11# connecteurs.12# Module : immoka13# Repository : https://git.spboucher.ai/immo-ka14# Created : 2026-08-1215# Last Modified : 2026-08-2716#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author : Simon-Pierre Boucher22# Position : Professor of Finance23# Institution : Université du Québec en Outaouais (UQO)24# Department : Département des sciences administratives25# Organization : SP Boucher26#27# Website : https://spboucher.ai28# Git : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General : info@spboucher.ai35# Professional : contact@spboucher.ai36# Direct : simon@spboucher.ai37# Research : research@spboucher.ai38# Development : dev@spboucher.ai39# Support : support@spboucher.ai40# Security/Admin : admin@spboucher.ai41# Notifications : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification : Public68# Distribution : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License : None specified (no license file in this repository)82# Maintainer : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889# -----------------------------------------------------------------------------90# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)91# Auteur : Simon-Pierre Boucher — contact@spboucher.ai92# normalize.py : couche de normalisation commune (prix, types, adresses…)93# -----------------------------------------------------------------------------94"""Fonctions de normalisation partagées par tous les connecteurs.9596Les connecteurs remplissent les champs bruts tels que vus sur le site source ;97`PropertyListing.finalize()` (schema.py) appelle ces fonctions pour produire98des valeurs canoniques comparables entre agences.99"""100from __future__ import annotations101102import re103import unicodedata104105__all__ = [106 "strip_accents", "clean_address", "parse_price", "price_is_from",107 "parse_int", "parse_float", "parse_area_sqft", "parse_lot_sqft",108 "parse_year", "normalize_property_type", "extract_bedrooms_bathrooms",109 "clean_title", "clean_description",110]111112113def strip_accents(text: str) -> str:114 return "".join(c for c in unicodedata.normalize("NFD", text or "")115 if unicodedata.category(c) != "Mn")116117118_SMALL_WORDS = {"a", "à", "au", "aux", "avec", "de", "des", "du", "en", "et",119 "la", "le", "les", "ou", "pour", "sur", "sous", "un", "une"}120121122def clean_title(text: str) -> str:123 """Titre propre : espaces normalisés, et les titres CRIÉS EN MAJUSCULES124 (fréquents chez certaines sources) ramenés en casse naturelle — chaque mot125 capitalisé sauf les mots-outils (les noms de villes restent capitalisés)."""126 t = re.sub(r"\s+", " ", (text or "")).strip()127 letters = [c for c in t if c.isalpha()]128 if len(letters) >= 8 and sum(c.isupper() for c in letters) / len(letters) > 0.85:129 words = []130 for i, w in enumerate(t.lower().split(" ")):131 words.append(w if (i and w in _SMALL_WORDS) else w[:1].upper() + w[1:])132 t = " ".join(words)133 return t134135136_TAG_RE = re.compile(r"<[^>]+>")137_BR_RE = re.compile(r"<br\s*/?>|</p>|</div>|</li>", re.I)138139140def clean_description(text: str) -> str:141 """Description sans HTML brut visible : balises retirées (sauts de ligne142 préservés), entités décodées, espaces/blancs normalisés."""143 import html as _html144 t = text or ""145 if "<" in t and ">" in t:146 t = _BR_RE.sub("\n", t)147 t = _TAG_RE.sub(" ", t)148 t = _html.unescape(t)149 t = re.sub(r"[ \t]+", " ", t)150 t = re.sub(r" ?\n ?", "\n", t)151 t = re.sub(r"\n{3,}", "\n\n", t)152 return t.strip()153154155def clean_address(text: str) -> str:156 """Nettoie une adresse civique (espaces, virgules doublées, apostrophes)."""157 t = re.sub(r"\s+", " ", (text or "").replace("’", "'")).strip()158 t = re.sub(r"\s*,\s*", ", ", t)159 t = re.sub(r"(, )+", ", ", t).strip(", ")160 return t161162163# ---------------------------------------------------------------------------164# Prix165# ---------------------------------------------------------------------------166167_PRICE_RE = re.compile(r"(\d[\d\s .,]*)\s*(?:\$|CAD)?", re.UNICODE)168169170def parse_price(label: str) -> float | None:171 """Extrait un prix de vente d'un libellé source.172173 Gère « 459 000 $ », « $459,000 », « 1 249 000$ +tx », « À partir de 399 900 $ ».174 Retourne None si aucun montant plausible (>= 10 000 $) n'est trouvé.175 """176 if not label:177 return None178 m = _PRICE_RE.search(label.replace(" ", " ").replace(" ", " "))179 if not m:180 return None181 raw = m.group(1).strip()182 # « 459 000 » / « 459,000 » / « 459000.00 » — retirer les séparateurs de milliers183 raw = raw.replace(" ", "")184 if "," in raw and "." in raw:185 raw = raw.replace(",", "") # 459,000.00186 elif raw.count(",") == 1 and len(raw.split(",")[1]) == 2:187 raw = raw.replace(",", ".") # 459000,00 (décimale FR)188 else:189 raw = raw.replace(",", "")190 try:191 value = float(raw)192 except ValueError:193 return None194 return value if value >= 10_000 else None195196197def price_is_from(label: str) -> bool:198 key = strip_accents((label or "").lower())199 return any(k in key for k in ("a partir", "starting", "from", "des "))200201202# ---------------------------------------------------------------------------203# Nombres génériques204# ---------------------------------------------------------------------------205206def parse_int(text) -> int | None:207 if text is None:208 return None209 if isinstance(text, (int, float)):210 return int(text)211 m = re.search(r"\d+", str(text))212 return int(m.group()) if m else None213214215def parse_float(text) -> float | None:216 if text is None:217 return None218 if isinstance(text, (int, float)):219 return float(text)220 m = re.search(r"\d[\d\s]*(?:[.,]\d+)?", str(text))221 if not m:222 return None223 try:224 return float(m.group().replace(" ", "").replace(",", "."))225 except ValueError:226 return None227228229_SQFT_RE = re.compile(r"([\d\s ,.]+)\s*(pi2|pi²|pc|sq\.?\s*?ft|ft2|ft²)",230 re.IGNORECASE)231_SQM_RE = re.compile(r"([\d\s ,.]+)\s*(m2|m²|mc)", re.IGNORECASE)232233234def parse_area_sqft(text: str) -> float | None:235 """Superficie habitable en pi² (convertit les m² au besoin)."""236 if not text:237 return None238 t = text.replace(" ", " ")239 m = _SQFT_RE.search(t)240 if m:241 v = parse_float(m.group(1))242 return round(v) if v and v > 50 else None243 m = _SQM_RE.search(t)244 if m:245 v = parse_float(m.group(1))246 return round(v * 10.7639) if v and v > 5 else None247 return None248249250def parse_lot_sqft(text: str) -> float | None:251 """Superficie de terrain en pi² — mêmes unités que parse_area_sqft."""252 return parse_area_sqft(text)253254255# « 1959 », « 2018 (Neuf) », « 1975, rénové »… mais JAMAIS « 20' X 34' irr. »256# ni « À construire » : la valeur doit COMMENCER par une année plausible.257_YEAR_RE = re.compile(r"^\s*(1[6-9]\d{2}|20[0-4]\d)\s*(?:$|[(,])")258259260def parse_year(text) -> int | None:261 """Année de construction plausible (1600-2049) depuis une valeur `details`.262263 Volontairement strict (année en tête de valeur, seule ou suivie d'une264 parenthèse/virgule) pour ne jamais promouvoir un libellé parasite vers la265 colonne year_built."""266 if text is None:267 return None268 if isinstance(text, (int, float)):269 y = int(text)270 return y if 1600 <= y <= 2049 else None271 m = _YEAR_RE.match(str(text))272 return int(m.group(1)) if m else None273274275# ---------------------------------------------------------------------------276# Type de propriété277# ---------------------------------------------------------------------------278279# Vocabulaire canonique d'Immo-Ka (affiché dans les filtres du frontend)280_TYPE_MAP = [281 # (mots-clés dans le texte source normalisé, type canonique)282 (("plain-pied", "bungalow",), "Maison"),283 (("maison a etages", "a etage", "deux etages", "cottage",), "Maison"),284 (("maison mobile", "unimodulaire", "mobile home", "manufactured home",),285 "Maison mobile"),286 (("jumele", "semi-detache", "semi detache", "semi-detached", "semi detached",),287 "Jumelé"),288 (("maison de ville", "townhouse", "en rangee", "row house", "row / town",),289 "Maison de ville"),290 (("unifamiliale", "maison", "house", "residence", "split", "detached",291 "single family",), "Maison"),292 (("condo", "copropriete", "appartement", "apartment", "loft", "penthouse",293 "studio",), "Condo"),294 (("duplex",), "Duplex"),295 (("triplex",), "Triplex"),296 (("quadruplex", "quintuplex", "multiplex", "multilogement", "multi-logement",297 "immeuble a revenus", "revenus", "multi-family", "multi family",298 "fourplex",), "Multiplex"),299 (("chalet", "cottage 4 saisons", "acces au plan d'eau", "bord de l'eau",300 "recreational",), "Chalet"),301 (("terre", "terrain", "lot ", "land",), "Terrain"),302 (("ferme", "fermette", "agricole", "agriculture", "hobby farm", "farm",303 "acreage",), "Fermette/Agricole"),304 # vocabulaire des fiches enrichies : « 4 logements », « propriété à revenu »305 (("logements", "logement/", "unites et +", "revenu",), "Multiplex"),306 (("bi generation", "bi-generation", "bigeneration", "intergeneration",),307 "Maison"),308 (("domaine et villa", "villa", "domaine",), "Maison"),309 (("commercial", "commerce", "industriel", "industrie", "bureau", "local",310 "entreprise", "batisse", "restaurant", "depanneur", "hotel", "motel",311 "garage/", "concessionnaire", "coiffure", "esthetique", "camping",312 "retail", "office", "industrial", "warehouse", "business",),313 "Commercial"),314]315316317def normalize_property_type(text: str) -> str:318 import html as _html319 key = strip_accents(_html.unescape(text or "").strip().lower())320 if not key:321 return ""322 for keywords, canon in _TYPE_MAP:323 if any(k in key for k in keywords):324 return canon325 return _html.unescape(text).strip().capitalize()326327328# ---------------------------------------------------------------------------329# Chambres / salles de bains depuis du texte libre330# ---------------------------------------------------------------------------331332_BED_RE = re.compile(r"(\d+)\s*(?:ch(?:ambre)?s?|cac|bed(?:room)?s?)\b",333 re.IGNORECASE)334_BATH_RE = re.compile(r"(\d+)\s*(?:sdb|salle?s?\s+de\s+bains?|bath(?:room)?s?)",335 re.IGNORECASE)336337338def extract_bedrooms_bathrooms(text: str) -> tuple[int | None, int | None]:339 if not text:340 return None, None341 beds = _BED_RE.search(text)342 baths = _BATH_RE.search(text)343 return (int(beds.group(1)) if beds else None,344 int(baths.group(1)) if baths else None)345