Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/guidehabitation.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1813# 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/guidehabitation.py : Guide Habitation (guidehabitation.ca)91# Répertoire de référence des PROJETS NEUFS au Québec (condos et maisons92# neuves des promoteurs). Pages région /fr/projets-immobiliers/{region}/93# rendues serveur avec microdonnées schema.org complètes par carte projet :94# adresse (streetAddress), ville, GPS, prix « À partir de » (itemprop=price),95# type (SingleFamilyResidence → maison, ApartmentComplex → condo),96# description, chambres offertes, photo. Aucune clé, aucun rendu JS.97# On écarte les projets LOCATIFS (prix mensuel / « locatif » dans le texte) :98# Immo-Ka couvre le neuf À VENDRE. external_id = data-id du projet.99#100# Page détail projet : UN gros JSON-LD RealEstateListing très riche —101# about.articleBody (présentation longue, pseudo-markdown), mainEntity.image102# (galerie complète pleine résolution, ordre d'origine), mainEntity.geo,103# amenityFeature, offers[] (promoteur offeredBy : nom/téléphone/site,104# chambres, garantie, date de livraison), additionalProperty (statut du105# projet, site web externe). Enrichissement plafonné + cache (du.enrich).106# -----------------------------------------------------------------------------107from __future__ import annotations108109import html as _html110import os111import re112113from .base import BaseConnector114from . import _detailutil as du115from ..schema import PropertyListing116117SITE = "https://www.guidehabitation.ca"118DETAIL_LIMIT = int(os.environ.get("IMMOKA_GH_DETAIL_LIMIT", "150"))119120# Régions du répertoire (repli si le sitemap est indisponible).121REGIONS = ["montreal", "monteregie", "laval", "laurentides", "lanaudiere",122 "quebec", "estrie", "outaouais", "mauricie"]123124_SITEMAP_REGION_RE = re.compile(r'/fr/projets-immobiliers/([a-z-]+)/')125_CARD_SPLIT_RE = re.compile(r'(?=<article class="project-card )')126_ID_RE = re.compile(r'data-id="(\d+)"')127_URL_RE = re.compile(r'href="(https://www\.guidehabitation\.ca/fr/\d+/[^"]+)"')128_IMG_RE = re.compile(r'<img[^>]+src="([^"]+)"')129_META_RE = re.compile(r'itemprop="(name|streetAddress|addressLocality|latitude|'130 r'longitude|price)"[^>]*content="([^"]*)"')131_LOCALITY_RE = re.compile(r'itemprop="addressLocality">([^<]*)<')132_NAME_H3_RE = re.compile(r'<h3 itemprop="name">([^<]*)</h3>')133_DESC_RE = re.compile(r'itemprop="description">([^<]*)<')134_TYPE_RE = re.compile(r'itemtype="https://schema\.org/(SingleFamilyResidence|'135 r'ApartmentComplex|Residence)"')136_BEDROOMS_RE = re.compile(r'class="card-bedrooms">([^<]*)<')137_PRICE_TXT_RE = re.compile(r'À partir de\s*([\d\s ,.]+)\s*\$')138_RENTAL_RE = re.compile(r'locati|à louer|for rent', re.I)139_SQFT_RE = re.compile(r'[Ss]uperficie habitable[\s ]*:?[\s ]*'140 r'([\d][\d\s ,]*)\s*pi')141142# En deçà de ce prix « à partir de », c'est un loyer mensuel (projet locatif).143MIN_SALE_PRICE = 50_000144145146class GuideHabitationConnector(BaseConnector):147 source_id = "guidehabitation"148 request_delay = 1.0149150 def _regions(self) -> list[str]:151 try:152 xml = self.get(f"{SITE}/sitemap.xml").text153 found = sorted({m.group(1) for m in _SITEMAP_REGION_RE.finditer(xml)})154 if found:155 return found156 except Exception:157 pass158 return REGIONS159160 def fetch(self) -> list[PropertyListing]:161 by_id: dict[str, PropertyListing] = {}162 for region in self._regions():163 try:164 html = self.get(f"{SITE}/fr/projets-immobiliers/{region}/").text165 except Exception:166 continue167 for card in _CARD_SPLIT_RE.split(html):168 if 'data-id="' not in card:169 continue170 lst = self._to_listing(card, region)171 if lst and lst.external_id not in by_id:172 by_id[lst.external_id] = lst173 listings = list(by_id.values())174 du.enrich(self, listings, DETAIL_LIMIT, _parse_gh_detail, key="v1")175 return listings176177 def _to_listing(self, card: str, region: str) -> PropertyListing | None:178 mid = _ID_RE.search(card)179 murl = _URL_RE.search(card)180 if not mid or not murl:181 return None182 meta = {k: _html.unescape(v).strip() for k, v in _META_RE.findall(card)}183 name = meta.get("name") or ""184 mh3 = _NAME_H3_RE.search(card)185 if mh3:186 name = _html.unescape(mh3.group(1)).strip() or name187 desc = ""188 mdesc = _DESC_RE.search(card)189 if mdesc:190 desc = _html.unescape(mdesc.group(1)).strip()191 # prix « À partir de » — absent ou mensuel (locatif) → hors périmètre192 price = None193 try:194 price = float(meta.get("price"))195 except (TypeError, ValueError):196 mtxt = _PRICE_TXT_RE.search(card)197 if mtxt:198 try:199 price = float(re.sub(r"[\s ,]", "", mtxt.group(1)))200 except ValueError:201 price = None202 if price is None or price < MIN_SALE_PRICE:203 return None204 if _RENTAL_RE.search(name) or _RENTAL_RE.search(desc):205 return None206 mtype = _TYPE_RE.search(card)207 ptype = {"SingleFamilyResidence": "Maison",208 "ApartmentComplex": "Condo"}.get(209 mtype.group(1) if mtype else "", "")210 city = meta.get("addressLocality") or ""211 if not city:212 mloc = _LOCALITY_RE.search(card)213 if mloc:214 city = _html.unescape(mloc.group(1)).strip()215 address = meta.get("streetAddress") or ""216 # « Chemin du Golf, Sainte-Julie, QC, Canada » → rue seulement217 address = re.sub(r",\s*(QC|Québec|Quebec)\b.*$", "", address).strip()218 if city and address.lower().endswith(", " + city.lower()):219 address = address[: -(len(city) + 2)].strip().rstrip(",")220 lst = PropertyListing(221 source=self.source_id,222 external_id=mid.group(1),223 url=murl.group(1),224 title=name,225 address=address or name,226 city=city,227 property_type=ptype,228 price=price,229 price_label=f"À partir de {price:,.0f} $".replace(",", " "),230 description=desc,231 broker_name="Guide Habitation — projet neuf",232 agency="Guide Habitation (projets neufs)",233 )234 mimg = _IMG_RE.search(card)235 if mimg:236 lst.images = [mimg.group(1)]237 try:238 lst.lat = float(meta.get("latitude"))239 lst.lng = float(meta.get("longitude"))240 except (TypeError, ValueError):241 pass242 mbeds = _BEDROOMS_RE.search(card)243 if mbeds:244 beds = re.findall(r"(\d+)\s*ch", mbeds.group(1))245 if beds:246 lst.bedrooms = int(beds[0]) # minimum offert247 lst.details["Chambres offertes"] = _html.unescape(248 mbeds.group(1)).strip()249 lst.details["Projet neuf"] = True250 return lst251252253def _clean_md(text: str) -> str:254 """articleBody pseudo-markdown -> texte propre (garde les paragraphes)."""255 t = _html.unescape(text).replace("\xa0", " ")256 t = re.sub(r"\*\*+", "", t) # **gras**257 t = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", t) # [lien](url)258 t = re.sub(r"^[\s]*[-•#]+\s*", "", t, flags=re.M) # puces/titres259 t = re.sub(r"[ \t]+", " ", t)260 return re.sub(r"\n{3,}", "\n\n", t).strip()261262263def _parse_gh_detail(html: str) -> dict:264 """Fiche projet Guide Habitation : tout est dans le JSON-LD RealEstateListing."""265 out: dict = {}266 node = None267 for n in du.ld_nodes(html):268 t = n.get("@type")269 if "RealEstateListing" in (t if isinstance(t, list) else [t]):270 node = n271 break272 if not node:273 return out274275 about = node.get("about") or {}276 body = str(about.get("articleBody") or "")277 if body:278 desc = _clean_md(body)279 if desc:280 out["description"] = desc281282 main = node.get("mainEntity") or {}283 imgs = main.get("image") or []284 if isinstance(imgs, str):285 imgs = [imgs]286 imgs = [u for u in imgs if isinstance(u, str) and u.startswith("http")]287 if imgs:288 out["images"] = imgs289 geo = main.get("geo") or {}290 try:291 lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))292 if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:293 out["lat"], out["lng"] = lat, lng294 except (TypeError, ValueError):295 pass296297 details: dict = {}298 features: list[str] = []299 for af in main.get("amenityFeature") or []:300 v = str(af.get("value") or "").strip()301 if v and v.lower() not in ("true", "false"):302 features.append(v)303 elif v.lower() == "true" and af.get("name"):304 features.append(str(af["name"]))305 if features:306 out["features"] = features307308 for ap in node.get("additionalProperty") or []:309 pid, val = ap.get("propertyID") or "", str(ap.get("value") or "").strip()310 if not val:311 continue312 if pid == "gh:status":313 details["Statut du projet"] = val314 elif pid == "gh:deliveryDate":315 details["Livraison"] = val.split(" ")[0]316 elif ap.get("name") == "externalUrl":317 details["Site du projet"] = val318319 # offres (par modèle) : promoteur, chambres min, garantie320 offers = node.get("offers") or []321 if isinstance(offers, dict):322 offers = [offers]323 beds = []324 for of in offers:325 item = of.get("itemOffered") or {}326 try:327 beds.append(int(item.get("numberOfBedrooms")))328 except (TypeError, ValueError):329 pass330 if of.get("warranty") and "Garantie" not in details:331 details["Garantie"] = str(of["warranty"])332 by = of.get("offeredBy") or {}333 if by.get("name") and "broker_name" not in out:334 out["broker_name"] = str(by["name"])335 if by.get("telephone"):336 out["broker_phone"] = str(by["telephone"])337 if beds:338 out["bedrooms"] = min(beds)339340 # superficies habitables des modèles (texte de présentation) : minimum341 # offert (cohérent avec le prix « à partir de »)342 areas = []343 for m in _SQFT_RE.finditer(body):344 try:345 areas.append(float(re.sub(r"[^\d]", "", m.group(1))))346 except ValueError:347 pass348 areas = [a for a in areas if 300 <= a <= 20000]349 if areas:350 out["area_sqft"] = min(areas)351 if len(areas) > 1:352 details["Superficies offertes"] = (353 f"{min(areas):,.0f} à {max(areas):,.0f} pi²".replace(",", " "))354355 if details:356 out["details"] = details357 return out358