Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/sutton.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1814#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/sutton.py : Groupe Sutton Québec (suttonquebec.com)91# Site rendu serveur : chaque page de résultats publie 10 propriétés en92# JSON-LD schema.org (ItemList), avec prix, chambres, salles de bains,93# superficie et adresse. Les photos suivent le motif immo.vrtx.co/pic450/{id}.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import html as _html98import os99import re100101from .base import BaseConnector102from . import _detailutil as du103from .jsonld import item_list_elements, sqm_to_sqft104from ..schema import PropertyListing105106BASE = "https://www.suttonquebec.com"107DETAIL_LIMIT = int(os.environ.get("IMMOKA_SUTTON_DETAIL_LIMIT", "400"))108# toutes les photos de la fiche (la liste n'en montre que quelques-unes)109_DET_IMG_RE = re.compile(r'https://immo\.vrtx\.co/pic\d+/(\d+(?:-\d+)?)\.(?:jpg|jpeg|png|webp)', re.I)110_DESC_RE = re.compile(r'Description de la propri[ée]t[ée](?:\s+[àa]\s+vendre)?[^A-Za-z0-9]*(.*?)'111 r'(?:Caract[ée]ristiques|Pi[èe]ce|Inclusions|Exclusions|Addenda|$)', re.I | re.S)112_ROOM_ROW_RE = re.compile(113 r'([A-ZÀ-Ÿ][^\d|]{2,38}?)\s+(\d[\d.,]*\s*[xX]\s*\d[\d.,]*)\s*P?\s+'114 r'([A-Za-zÀ-ÿ/ -]{3,30}?)\s+(RC|SS|AU|\d[eE]?r?e?)\b')115# Pages de résultats couvrant le résidentiel à vendre au Québec.116LISTING_PAGES = [117 "/fr/maisons-a-vendre.html",118 "/fr/condos-lofts-appartements-a-vendre.html",119 "/fr/chalets-a-vendre.html",120 "/fr/fermes-fermettes-a-vendre.html",121]122MAX_PAGES = 60 # garde-fou (10 propriétés/page)123IMG_RE = re.compile(r'https://immo\.vrtx\.co/pic\d+/(\d+)(?:-\d+)?\.(?:jpg|jpeg|png|webp)',124 re.I)125NOINS_RE = re.compile(r'noInscription=(\d+)')126127# Sitemap : couverture EXHAUSTIVE (l'index /sitemap.cfm pointe vers des128# sitemaps d'inscriptions paginés). typeInscription=1 = à vendre, =2 = à louer.129SITEMAP_INDEX = f"{BASE}/sitemap.cfm"130SITEMAP_MAX_PAGES = 40 # garde-fou (≈12 pages réelles × ~1000)131_SM_SUB_RE = re.compile(r'sitemap_inscription\.cfm\?[^<"\s]+', re.I)132_SM_LOC_RE = re.compile(133 r'https://www\.suttonquebec\.com/fr/inscription/([^<"?]+)\.html\?'134 r'noInscription=(\d+)&(?:amp;)?typeInscription=(\d)', re.I)135136137class SuttonConnector(BaseConnector):138 source_id = "sutton"139 request_delay = 0.5140141 def fetch(self) -> list[PropertyListing]:142 by_id: dict[str, PropertyListing] = {}143 # 1) couverture exhaustive via le sitemap (adresse/type depuis le slug)144 for slug, centris, url in self._sitemap_listings():145 if centris in by_id:146 continue147 ptype, addr, city = _from_slug(slug)148 by_id[centris] = PropertyListing(149 source=self.source_id, external_id=centris, url=url,150 title=addr or _deslug(slug), address=addr, city=city,151 property_type=ptype, mls=centris,152 broker_name="Groupe Sutton Québec",153 )154 listings = list(by_id.values())155 # fiche détail : prix, chambres/sdb, galerie complète (~80 photos),156 # description, pièces, inclusions, caractéristiques — plafonné, cache157 # accumulé entre cycles (tout le parc finit enrichi au fil des syncs).158 # v5 = + année (« Construction : »), superficies (Aire habitable /159 # Terrain superficie), taxes, évaluation, frais de copropriété, revenus160 du.enrich(self, listings, DETAIL_LIMIT, parse_sutton_detail, key="v5")161 for lst in listings:162 office = lst.details.pop("__agency", "")163 lst.agency = office or "Groupe Sutton Québec"164 return listings165166 def _sitemap_listings(self):167 """Itère (slug, centris, url) de toutes les inscriptions À VENDRE."""168 try:169 index = self.get(SITEMAP_INDEX).text170 except Exception:171 return172 subs = []173 for s in _SM_SUB_RE.findall(index):174 s = s.replace("&", "&")175 if s not in subs:176 subs.append(s)177 if not subs: # repli : pagination directe178 subs = [f"sitemap_inscription.cfm?page={p}&platine=0"179 for p in range(1, 14)] + ["sitemap_inscription.cfm?platine=1"]180 seen = set()181 for sub in subs[:SITEMAP_MAX_PAGES]:182 try:183 xml = self.get(f"{BASE}/{sub}").text184 except Exception:185 continue186 for m in _SM_LOC_RE.finditer(xml):187 slug, centris, typ = m.group(1), m.group(2), m.group(3)188 if typ != "1" or centris in seen: # 1 = à vendre uniquement189 continue190 seen.add(centris)191 url = (f"{BASE}/fr/inscription/{slug}.html"192 f"?noInscription={centris}&typeInscription=1")193 yield slug, centris, url194195 def _fetch_section(self, path: str, out: dict) -> None:196 page = 1197 while page <= MAX_PAGES:198 url = f"{BASE}{path}?page={page}"199 try:200 html = self.get(url).text201 except Exception:202 break203 elems = item_list_elements(html)204 if not elems:205 break206 images_by_id = self._images_by_id(html)207 new = 0208 for el in elems:209 lst = self._to_listing(el, images_by_id)210 if lst and lst.uid not in out:211 out[lst.uid] = lst212 new += 1213 # dernière page : moins d'items que la pleine page, ou rien de neuf214 if len(elems) < 10 or new == 0:215 break216 page += 1217218 @staticmethod219 def _images_by_id(html: str) -> dict[str, list[str]]:220 groups: dict[str, list[str]] = {}221 for m in IMG_RE.finditer(html):222 groups.setdefault(m.group(1), [])223 if m.group(0) not in groups[m.group(1)]:224 groups[m.group(1)].append(m.group(0))225 return groups226227 def _to_listing(self, el: dict, images_by_id: dict) -> PropertyListing | None:228 item = el.get("item", el)229 url = item.get("url") or el.get("url") or ""230 if not url:231 return None232 if url.startswith("fr/") or url.startswith("/fr/"):233 url = f"{BASE}/{url.lstrip('/')}"234 m = NOINS_RE.search(url) or NOINS_RE.search(el.get("url", ""))235 external_id = m.group(1) if m else url.rsplit("/", 1)[-1].split(".")[0]236237 addr = el.get("address") or item.get("address") or {}238 offers = el.get("offers") or item.get("offers") or {}239 price = offers.get("price")240 try:241 price = float(price) if price is not None else None242 except (TypeError, ValueError):243 price = None244245 area = None246 fs = item.get("floorSize") or {}247 if isinstance(fs, dict) and fs.get("value"):248 val = fs["value"]249 # unitCode MTK = m² ; sinon on suppose des pi². Convertit si plausible.250 if fs.get("unitCode") == "MTK" and float(val) < 400:251 area = sqm_to_sqft(val)252 else:253 try:254 area = round(float(val))255 except (TypeError, ValueError):256 area = None257258 return PropertyListing(259 source=self.source_id,260 external_id=str(external_id),261 url=url,262 title=(item.get("name") or el.get("name") or "").strip(),263 address=addr.get("streetAddress", ""),264 sector=addr.get("addressLocality", ""),265 city=addr.get("addressLocality", ""),266 region=addr.get("addressRegion", ""),267 property_type=item.get("@type", ""),268 price=price,269 price_label=(f"{price:,.0f} $".replace(",", " ") if price else ""),270 bedrooms=_as_int(item.get("numberOfBedrooms")),271 bathrooms=_as_int(item.get("numberOfBathroomsTotal")),272 area_sqft=area,273 images=images_by_id.get(str(external_id), []),274 broker_name="Groupe Sutton Québec",275 )276277278def _as_int(v):279 try:280 return int(float(v))281 except (TypeError, ValueError):282 return None283284285def _deslug(s: str) -> str:286 return re.sub(r"\s+", " ", s.replace("-", " ")).strip().title()287288289# villes/arrondissements composés fréquents dans les slugs Sutton (fin du slug)290_CITY_HINTS = (291 "montreal-le-plateau-mont-royal", "montreal-ville-marie", "montreal-rosemont-la-petite-patrie",292 "montreal-le-sud-ouest", "montreal-cote-des-neiges-notre-dame-de-grace", "montreal-ahuntsic-cartierville",293 "montreal-villeray-saint-michel-parc-extension", "montreal-mercier-hochelaga-maisonneuve",294 "montreal-riviere-des-prairies-pointe-aux-trembles", "montreal-verdun-ile-des-soeurs",295 "montreal-saint-laurent", "montreal-lasalle", "montreal-outremont", "montreal-anjou",296 "montreal-pierrefonds-roxboro", "trois-rivieres", "saint-jean-sur-richelieu",297 "salaberry-de-valleyfield", "mont-saint-hilaire", "notre-dame-de-l-ile-perrot",298 "vaudreuil-dorion", "sainte-adele", "sainte-therese", "saint-jerome", "levis", "quebec",299 "laval", "gatineau", "longueuil", "brossard", "sherbrooke", "granby", "magog",300)301302303def _from_slug(slug: str) -> tuple[str, str, str]:304 """« maison-de-plain-pied-a-vendre-522-cedar-street-beaconsfield »305 -> (type, adresse, ville). Best-effort (l'adresse exacte vient de la fiche)."""306 m = re.search(r"^(.*?)-a-vendre-(.+)$", slug, re.I)307 if not m:308 return "", _deslug(slug), ""309 ptype = _deslug(m.group(1))310 rest = m.group(2).lower()311 city = ""312 for hint in _CITY_HINTS:313 if rest.endswith("-" + hint) or rest == hint:314 city = _deslug(hint)315 rest = rest[: -len(hint)].rstrip("-")316 break317 else:318 # sinon : dernier token comme ville (approx ; corrigé par la fiche détail)319 parts = rest.rsplit("-", 1)320 if len(parts) == 2 and not parts[1].isdigit():321 city, rest = _deslug(parts[1]), parts[0]322 return ptype, _deslug(rest), city323324325def _merge(dst: PropertyListing, src: PropertyListing) -> None:326 """Complète dst (issu du sitemap) avec les champs riches de src (JSON-LD)."""327 for f in ("price", "bedrooms", "bathrooms", "area_sqft"):328 if getattr(dst, f, None) in (None, 0) and getattr(src, f, None) not in (None, 0):329 setattr(dst, f, getattr(src, f))330 for f in ("address", "city", "sector", "region", "price_label", "property_type"):331 if not getattr(dst, f, "") and getattr(src, f, ""):332 setattr(dst, f, getattr(src, f))333 if len(src.images) > len(dst.images):334 dst.images = src.images335336337# libellés des tableaux de la fiche Sutton retenus dans details (les lignes de338# pièces « Salon 12.8x11.10 P »… sont déjà captées à part dans details.pieces)339_TABLE_LABELS = {340 "Aire habitable", "Terrain superficie", "Terrain dim.", "Batisse dim.",341 "Frais de copropriété", "Revenu", "Taxes municipales", "Taxes scolaires",342 "Coût d'énergie", "Zonage", "Sous-sol", "Toiture", "Fondation",343 "Mode de chauffage", "Énergie pour le chauffage",344 "Approvisionnement en eau", "Système d'égouts", "Stationnement (total)",345 "Garage", "Piscine", "Proximité", "Fenêtres", "Revêtements",346}347348349def parse_sutton_detail(html: str) -> dict:350 """Fiche Sutton : galerie complète, description, pièces (dimensions), inclusions."""351 out: dict = {}352 # photos : normaliser toute taille -> pic450, dédoublonner par id-index353 seen, imgs = {}, []354 for m in _DET_IMG_RE.finditer(html):355 key = m.group(1)356 if key not in seen:357 seen[key] = 1358 imgs.append(f"https://immo.vrtx.co/pic450/{key}.jpg")359 if imgs:360 out["images"] = imgs361362 text = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", html)))363364 # prix : premier montant du texte (le prix demandé précède évaluation/taxes)365 for mnt in re.findall(r"([\d][\d ]{3,})\s*\$", text):366 val = _as_int(mnt.replace(" ", "").replace("\xa0", ""))367 if val and val >= 20000:368 out["price"] = float(val)369 out["price_label"] = f"{val:,.0f} $".replace(",", " ")370 break371 mb = re.search(r"(\d+)\s*chambre", text, re.I)372 if mb:373 out["bedrooms"] = int(mb.group(1))374 ms = re.search(r"(\d+)\s*salle[s]?\s*de\s*bain", text, re.I)375 if ms:376 out["bathrooms"] = int(ms.group(1))377378 md = _DESC_RE.search(text)379 if md:380 desc = md.group(1).strip()381 if len(desc) > 30:382 out["description"] = desc[:4000]383384 # pièces : « Nom DimxDim P Revêtement Niveau »385 rooms = []386 for m in _ROOM_ROW_RE.finditer(text):387 nom = m.group(1).strip(" -")388 # retirer l'en-tête de tableau qui peut coller au 1er nom389 nom = re.sub(r"^.*?(?:Niveau|Rev[êe]tement|Dimension)\s+", "", nom).strip(" -")390 if not nom or nom.lower() in ("pièce", "piece"):391 continue392 rooms.append({"nom": nom[:40], "dimensions": m.group(2).replace(" ", ""),393 "revetement": m.group(3).strip(), "niveau": m.group(4)})394 if rooms:395 out.setdefault("details", {})["pieces"] = rooms[:20]396397 # année de construction (bloc « Construction : 1975 » de l'entête)398 my = re.search(r"Construction\s*:\s*((?:1[6-9]|20)\d{2})\b", text)399 if my:400 out["year_built"] = int(my.group(1))401402 # tableaux « Dimensions / Caractéristiques / Dépenses » (<tr><td>l</td><td>v</td>)403 det2: dict = {}404 for lm, vm in re.findall(r"<tr>\s*<td>(.*?)</td>\s*<td>(.*?)</td>", html, re.S):405 label = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", lm))).strip()406 val = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", vm))).strip()407 if not label or not val or len(label) > 45 or len(val) > 90:408 continue409 if label in _TABLE_LABELS:410 det2[label] = val411 from ..normalize import parse_area_sqft, parse_lot_sqft412 if det2.get("Aire habitable"):413 a = parse_area_sqft(det2["Aire habitable"]) # « 188 MC (2024 pi2) »414 if a:415 out["area_sqft"] = a416 if det2.get("Terrain superficie"):417 t = parse_lot_sqft(det2["Terrain superficie"]) # « 685.4 MC (7378 pi2) »418 if t:419 out["lot_sqft"] = t420 # évaluation municipale : rendue hors <td> propre → texte aplati421 me = re.search(r"valuation municipale\s*:?\s*([\d\s ]{4,}\$"422 r"(?:\s*\(\d{4}\))?)", text)423 if me:424 det2["Évaluation municipale"] = re.sub(r"\s+", " ", me.group(1)).strip()425 if det2:426 out.setdefault("details", {}).update(det2)427428 # inclusions429 mi = re.search(r"Inclusions?\s*:?(.*?)(?:Exclusions|Addenda|Financ|$)", text, re.I | re.S)430 if mi:431 inc = mi.group(1).strip()432 feats = [s.strip() for s in re.split(r"[,;•]", inc) if 3 <= len(s.strip()) <= 90]433 if feats:434 out["features"] = feats[:20]435 _det = du.centris_details(du.flatten(html))436 if _det:437 out.setdefault("details", {}).update(_det)438439 # sous-agence (bureau) : lien /agence-immobiliere/NNN-<slug>.html440 ma = re.search(r'/agence-immobiliere/\d+-([a-z0-9-]+)\.html', html, re.I)441 if ma:442 out.setdefault("details", {})["__agency"] = _deslug(ma.group(1))443 return out444