Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/_detailutil.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1914#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: contact@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# -----------------------------------------------------------------------------88# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/_detailutil.py : utilitaires partagés d'enrichissement « page détail »91# Mutualise ce que chaque connecteur d'agence répète pour capter TOUTES les92# infos de la fiche source (comme remax_quebec.py) : description JSON-LD,93# coordonnées, aplatissement HTML, application au PropertyListing.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import html as _html98import json99import re100101from ..schema import PropertyListing102103_LD_RE = re.compile(r'<script[^>]+application/ld\+json[^>]*>(.*?)</script>', re.S | re.I)104_COORD_RE = re.compile(r'(?:google\.[^"\']*?[?&](?:q|query|ll|center)=|maps/@)'105 r'(-?\d{1,2}\.\d+)[ ,%+A-Za-z]+?(-?\d{2,3}\.\d+)')106_LD_PROP_TYPES = {"RealEstateListing", "Residence", "SingleFamilyResidence",107 "House", "Apartment", "Product", "Offer", "Place", "Accommodation"}108109110def ld_nodes(html: str):111 """Itère les objets JSON-LD (aplatis depuis @graph)."""112 for block in _LD_RE.findall(html):113 try:114 # strict=False : tolère les \n/\t bruts dans les chaînes (Yoamo…)115 data = json.loads(block, strict=False)116 except ValueError:117 continue118 graph = data.get("@graph", [data]) if isinstance(data, dict) else data119 for node in (graph if isinstance(graph, list) else [graph]):120 if isinstance(node, dict):121 yield node122123124def ld_description(html: str) -> str:125 """Description depuis un nœud JSON-LD de type propriété (le plus long trouvé)."""126 best = ""127 for n in ld_nodes(html):128 t = n.get("@type")129 types = t if isinstance(t, list) else [t]130 if any(x in _LD_PROP_TYPES for x in types) and n.get("description"):131 d = _html.unescape(str(n["description"])).strip()132 if len(d) > len(best):133 best = d134 return best135136137def gmaps_coords(html: str) -> tuple[float, float] | None:138 m = _COORD_RE.search(html)139 if not m:140 return None141 try:142 lat, lng = float(m.group(1)), float(m.group(2))143 except ValueError:144 return None145 if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:146 return lat, lng147 return None148149150def flatten(html: str) -> str:151 """HTML -> texte « valeur | libellé » pour extraire les tableaux Centris."""152 t = _html.unescape(re.sub(r"<[^>]+>", " | ", html))153 t = re.sub(r"[ \t\r\n]*\|[ \t\r\n|]*", " | ", t)154 return re.sub(r"[ \t]+", " ", t)155156157# libellés Centris standard cherchés dans « valeur | libellé » OU « libellé | valeur »158_LABELS = [159 "Type de propriété", "Genre de propriété", "Style de bâtiment",160 "Année de construction", "Superficie habitable", "Superficie du terrain",161 "Superficie du bâtiment (au sol)", "Nombre de pièces", "Nombre d'unités",162 "Stationnement (total)", "Stationnement", "Garage", "Système de chauffage",163 "Énergie pour le chauffage", "Type de fenestration", "Fenêtres", "Toiture",164 "Revêtement", "Sous-sol", "Piscine", "Zonage", "Système d'égouts",165 "Approvisionnement en eau", "Déménagement", "Taxes municipales",166 "Taxes scolaires", "Évaluation municipale (terrain)",167 "Évaluation municipale (bâtiment)", "Cuisine",168]169170171# en-têtes de section des fiches (jamais des valeurs valides)172_SECTION_HEADERS = {173 "bâtiment et intérieur", "particularités du bâtiment",174 "particularités du terrain", "particularités du site", "caractéristiques",175 "caractéristiques de la propriété", "détails financiers", "taxes et coûts",176 "taxes\xa0et\xa0coûts", "détails des pièces", "détails des rénovations",177 "inclusions et exclusions", "dimensions", "addenda", "frais mensuels",178 "évaluations", "équipement disponible", "dans les environs",179 "niveau", "revêtement", "détails", "taxes", "total", "pièce", "couvre-sol",180}181_LABELS_LOWER = {lb.lower() for lb in _LABELS}182183184def _plausible(label: str, val: str) -> bool:185 """Garde-fou : rejette les valeurs qui sont d'autres libellés/en-têtes de186 section (l'aplatissement « | » rend les deux ordres ambigus) et exige un187 format minimal pour les champs monétaires/numériques."""188 low = val.lower().strip(" :")189 if not val or len(val) > 55 or low == label.lower():190 return False191 if low in _LABELS_LOWER or low in _SECTION_HEADERS:192 return False193 if label.startswith(("Taxes", "Évaluation")) and "$" not in val:194 return False195 if label == "Année de construction" and not re.search(r"\b(1[6-9]|20)\d{2}\b", val):196 return False197 if label.startswith("Superficie") and not re.search(r"\d", val):198 return False199 return True200201202def centris_details(text: str) -> dict:203 """Extrait les caractéristiques Centris d'un texte aplati.204205 Les fiches Centris modernes rendent « Libellé | Valeur » (le libellé206 précède la valeur) — c'est l'ordre essayé en premier ; l'ancien ordre207 « Valeur | Libellé » reste en repli. Un garde-fou (_plausible) évite de208 capter l'en-tête de section ou le libellé voisin comme valeur."""209 out: dict = {}210 for label in _LABELS:211 lab = re.escape(label)212 for m in (re.search(lab + r"\s*(?:\(\d{4}\))?\s*\|\s*([^|]{1,55})", text),213 re.search(r"([^|]{1,55})\s*\|\s*" + lab + r"\b", text)):214 if m:215 val = re.sub(r"\s+", " ", m.group(1)).strip(" |")216 if _plausible(label, val):217 out[label] = val218 break219 return out220221222_INT_RE = re.compile(r"\d+")223224225def _int(v):226 if v is None:227 return None228 if isinstance(v, (int, float)):229 return int(v) or None230 m = _INT_RE.search(str(v))231 return int(m.group()) if m else None232233234def enrich(connector, listings, limit, parse_fn, key="v1", fetch_html=None):235 """Enrichit `listings` via leur page détail, avec cache BD + plafond `limit`.236237 - `parse_fn(html) -> dict` : extrait les champs riches d'une page détail.238 - `key` : versionne le cache (changer pour forcer un rafraîchissement).239 - `fetch_html(url) -> str` : par défaut connector.get(url).text ; passer240 connector.get_rendered pour les sites derrière Firecrawl/anti-bot.241 """242 if limit <= 0:243 return244 from .. import db245 fetch_html = fetch_html or (lambda u: connector.get(u).text)246 con = db.connect()247 budget = limit248 try:249 for lst in listings:250 cached = db.get_cached_detail(con, connector.source_id, lst.external_id, key)251 if cached is None:252 stale = db.get_stale_detail(con, connector.source_id, lst.external_id)253 if budget <= 0:254 # budget épuisé : payload périmé (ancienne clé) plutôt que255 # rien — la fiche garde ses photos/détails en attendant256 # son re-parse à un prochain cycle257 if stale:258 apply_detail(lst, stale)259 continue260 try:261 cached = parse_fn(fetch_html(lst.url))262 except Exception:263 cached = {}264 if not cached and stale:265 # échec transitoire (challenge, timeout) : on garde l'ancien266 # payload et on ne l'écrase pas — nouvel essai au prochain cycle267 apply_detail(lst, stale)268 budget -= 1269 continue270 db.put_cached_detail(con, connector.source_id, lst.external_id, key, cached)271 budget -= 1272 apply_detail(lst, cached)273 finally:274 con.close()275276277def apply_detail(lst: PropertyListing, d: dict) -> None:278 """Applique un payload détail au PropertyListing sans écraser les valeurs déjà279 présentes (sauf images : on garde la plus grande galerie)."""280 if not d:281 return282 imgs = d.get("images")283 if imgs and len(imgs) > len(lst.images):284 lst.images = imgs285 if d.get("features"):286 # fusionne en dédoublonnant287 seen = {f.lower() for f in lst.features}288 for f in d["features"]:289 if f.lower() not in seen:290 lst.features.append(f)291 seen.add(f.lower())292 if d.get("details"):293 lst.details.update(d["details"])294 if d.get("broker_name"):295 lst.broker_name = d["broker_name"]296 # description : on garde la plus riche (la fiche détail bat le résumé liste)297 if d.get("description") and len(d["description"]) > len(lst.description or ""):298 lst.description = d["description"]299 for f in ("price_label", "address", "city", "sector", "property_type"):300 if d.get(f) and not getattr(lst, f, ""):301 setattr(lst, f, d[f])302 for f in ("bedrooms", "bathrooms", "powder_rooms", "year_built",303 "area_sqft", "lot_sqft", "lat", "lng", "broker_phone", "price"):304 if d.get(f) is not None and getattr(lst, f, None) in (None, "", 0):305 setattr(lst, f, d[f])306