Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/remax_quebec.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/remax_quebec.py : RE/MAX Québec (remax-quebec.com)91# Le site interroge un index Meilisearch public (search-only key exposée dans92# la config de la page). L'index « inscriptions » couvre toute la province.93# Meilisearch plafonne à 1000 hits par requête (maxTotalHits) : on shard donc94# par région de tri d'acheminement postale (FSA, 3 premiers caractères) et on95# dédoublonne par numéro d'inscription. Couverture validée vs le total global.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import html as _html100import os101import re102103from .base import BaseConnector104from ..normalize import parse_area_sqft, parse_price105from ..schema import PropertyListing106107SEARCH_URL = "https://search.remax-quebec.com/indexes/inscriptions/search"108# Clé de recherche (search-only) exposée publiquement dans la config du site.109SEARCH_KEY = "b0b93998ab78573e8b937b528ad37d2ce3fbc97e07a9f2c909c4220db910c152"110SITE = "https://www.remax-quebec.com"111112# Territoires postaux du Québec : préfixes G, H et J.113FSA_LETTERS = ("G", "H", "J")114SOLD_TOKENS = ("vendu", "sold", "loué", "loue", "rented")115116# Enrichissement page détail (photos + specs) : plafonné par exécution pour117# garder chaque sync borné. Les fiches déjà en cache sont réutilisées gratis ;118# seules les nouvelles/modifiées consomment le budget. Sur plusieurs cycles,119# tout le parc finit enrichi. Surchargeable via IMMOKA_REMAX_DETAIL_LIMIT.120DETAIL_LIMIT = int(os.environ.get("IMMOKA_REMAX_DETAIL_LIMIT", "3000"))121122123class RemaxQuebecConnector(BaseConnector):124 source_id = "remax_quebec"125 request_delay = 0.15 # API JSON rapide ; on reste poli126 use_detail_cache = True # cache BD des pages détail (photos/specs)127128 def fetch(self) -> list[PropertyListing]:129 by_id: dict[int, dict] = {}130 for fsa in self._fsa_candidates():131 hits = self._search(fsa)132 for h in hits:133 nid = h.get("no_inscription")134 if nid is not None:135 by_id[nid] = h # dédoublonnage inter-shards136 listings = []137 for h in by_id.values():138 lst = self._to_listing(h)139 if lst is not None:140 listings.append(lst)141 self._enrich(listings)142 return listings143144 # -- enrichissement (photos + specs via la page détail) -------------------145 def _enrich(self, listings: list[PropertyListing]) -> None:146 from .. import db147 con = db.connect()148 budget = DETAIL_LIMIT149 for lst in listings:150 # v4 = tableau « Libellé | Valeur » + Détails financiers (taxes/éval) ;151 # bump de version = re-parse progressif de tout le parc dans le budget.152 key = f"v4|{lst.price_label or '-'}" # refetch aussi si le prix change153 cached = db.get_cached_detail(con, self.source_id, lst.external_id, key)154 if cached is None:155 stale = db.get_stale_detail(con, self.source_id, lst.external_id)156 if budget <= 0:157 # budget épuisé : payload périmé plutôt que rien (la fiche158 # garde photos/détails) — re-parse à un prochain cycle159 if stale:160 _apply_detail(lst, stale)161 continue162 cached = self._scrape_detail(lst.url)163 if not cached and stale:164 # échec transitoire : garder l'ancien payload sans l'écraser165 _apply_detail(lst, stale)166 budget -= 1167 continue168 db.put_cached_detail(con, self.source_id, lst.external_id, key, cached)169 budget -= 1170 _apply_detail(lst, cached)171 con.close()172173 def _scrape_detail(self, url: str) -> dict:174 try:175 html = self.get(url).text176 except Exception:177 return {}178 return parse_remax_detail(html)179180 # -- sharding --------------------------------------------------------------181 @staticmethod182 def _fsa_candidates():183 for letter in FSA_LETTERS:184 for digit in "0123456789":185 for last in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":186 yield f"{letter}{digit}{last}"187188 def _search(self, q: str) -> list[dict]:189 try:190 resp = self.post(191 SEARCH_URL,192 headers={"Authorization": f"Bearer {SEARCH_KEY}",193 "Content-Type": "application/json"},194 json={"q": q, "limit": 1000},195 )196 except Exception:197 return []198 data = resp.json()199 return data.get("hits", []) if isinstance(data, dict) else []200201 # -- mapping ---------------------------------------------------------------202 def _to_listing(self, h: dict) -> PropertyListing | None:203 nid = h.get("no_inscription")204 if nid is None:205 return None206 price_label = (h.get("display_price") or {}).get("fr", "") or ""207 # exclure les propriétés vendues / retirées (l'index les conserve)208 if any(tok in price_label.lower() for tok in SOLD_TOKENS):209 return None210211 slug = (h.get("slug") or {}).get("fr", "") or ""212 url = f"{SITE}/fr/proprietes/{slug}" if slug else f"{SITE}/fr"213 full_addr = (h.get("full_address") or {}).get("fr", "") or ""214 address, sector, city = _split_address(full_addr)215 prop_type, region = _from_slug(slug)216217 return PropertyListing(218 source=self.source_id,219 external_id=str(nid),220 url=url,221 title=full_addr,222 address=address,223 sector=sector,224 city=city,225 region=region,226 property_type=prop_type,227 price=parse_price(price_label),228 price_label=price_label,229 broker_name="RE/MAX Québec",230 )231232233# ---------------------------------------------------------------------------234# Analyse de l'adresse et du slug235# ---------------------------------------------------------------------------236237_PAREN_RE = re.compile(r"\(([^)]*)\)")238_POSTAL_RE = re.compile(r"[GHJ]\d[A-Z]\s?\d[A-Z]\d", re.I)239240241def _split_address(full: str) -> tuple[str, str, str]:242 """« 16146 Rue Forsyth, Montréal (Rivière-des-Prairies) (X), H1A5S9 »243 -> (adresse, secteur, ville)."""244 if not full:245 return "", "", ""246 parts = [p.strip() for p in full.split(",")]247 # retirer le code postal final248 if parts and _POSTAL_RE.search(parts[-1]):249 parts = parts[:-1]250 address = parts[0] if parts else ""251 city = sector = ""252 if len(parts) >= 2:253 muni = parts[1]254 parens = _PAREN_RE.findall(muni)255 city = _PAREN_RE.sub("", muni).strip()256 if parens:257 sector = parens[-1].strip()258 # secteur supplémentaire dans les champs suivants (avant le postal)259 for extra in parts[2:]:260 e = _PAREN_RE.sub("", extra).strip() or extra.strip()261 if e and not sector:262 sector = e263 return address, sector, city264265266_TYPE_SLUG = {267 "maison": "Maison", "house": "Maison",268 "condo": "Condo", "appartement": "Condo", "apartment": "Condo",269 "plex": "Multiplex", "duplex": "Duplex", "triplex": "Triplex",270 "terrain": "Terrain", "land": "Terrain",271 "chalet": "Chalet", "cottage": "Chalet",272 "fermette": "Fermette/Agricole", "ferme": "Fermette/Agricole",273 "commercial": "Commercial", "commerciale": "Commercial",274}275276277# ---------------------------------------------------------------------------278# Page détail : photos + description + caractéristiques279# ---------------------------------------------------------------------------280281_LD_RE = re.compile(r'<script[^>]+application/ld\+json[^>]*>(.*?)</script>', re.S | re.I)282# Les photos apparaissent dans plusieurs buckets de taille (www_full, _medium,283# _small…) selon le lazy-load ; on les capte toutes et on les normalise en284# pleine résolution, dédoublonnées par nom de fichier.285_IMG_RE = re.compile(286 r'https://media\.remax-quebec\.com/img/www_[a-z]+/[^"\'\\ ]+\.(?:jpg|jpeg|png|webp)',287 re.I)288_IMG_SIZE_RE = re.compile(r'/www_[a-z]+/', re.I)289# Dans le bandeau « Caractéristiques de la propriété », la valeur précède le290# libellé : « 2 (1 + 1) | Chambres », « 1 | Salle de bain ». Le tableau détaillé291# est lui rendu « Libellé | Valeur » (voir _DETAIL_LABELS plus bas).292_SPEC_RE = {293 "bedrooms": re.compile(r'(\d+)(?:\s*\([^)]*\))?\s*\|\s*Chambre', re.I),294 "bathrooms": re.compile(r'(\d+)\s*\|\s*Salle de bain', re.I),295 "powder_rooms": re.compile(r"(\d+)\s*\|\s*Salle d'eau", re.I),296 # « Année de construction | 1959 » (libellé avant la valeur)297 "year_built": re.compile(r'Ann[ée]+e de construction\s*\|\s*(\d{4})\b', re.I),298}299_NUM = r'[\d\s ,.]+'300_AREA_RE = re.compile(r'Superficie habitable\s*\|\s*(' + _NUM + r')\s*(m²|mc|pi²|pi|ft)', re.I)301_LOT_RE = re.compile(r'Superficie du terrain\s*\|\s*(' + _NUM + r')\s*(m²|mc|pi²|pi|ft)', re.I)302# Section « Détails financiers » : Évaluation municipale (AAAA) | Évaluation du303# terrain | X $ | Évaluation du bâtiment | Y $ | Total | Z $ | Taxes |304# Municipale (AAAA) | X $ | Scolaire (AAAA) | Y $ | Total | Z $305_MONEY = r'((?:\d[\d\s ]*)\$)'306_FIN_EVAL_LAND_RE = re.compile(r'Évaluation du terrain\s*\|\s*' + _MONEY)307_FIN_EVAL_BLDG_RE = re.compile(r'Évaluation du bâtiment\s*\|\s*' + _MONEY)308_FIN_EVAL_YEAR_RE = re.compile(r'Évaluation municipale\s*\((\d{4})\)')309_FIN_TAX_MUNI_RE = re.compile(r'\bMunicipale\s*(?:\((\d{4})\))?\s*\|\s*' + _MONEY, re.S)310_FIN_TAX_SCOL_RE = re.compile(r'\bScolaire\s*(?:\((\d{4})\))?\s*\|\s*' + _MONEY, re.S)311_COORD_RE = re.compile(r'query=(-?\d+\.\d+)%2C\+?(-?\d+\.\d+)')312_ROOM_RE = re.compile(r'rooms-details-section__vertical-table[^>]*>(.*?)</div>\s*</div>', re.S)313_QSTAT_RE = re.compile(314 r'quick-stat-text[^>]*>\s*<span[^>]*>\s*(.*?)\s*</span>\s*<span[^>]*>\s*(.*?)\s*</span>', re.S)315_INCL_RE = re.compile(r'inclusions-exclusions-section(.*?)(?:</section>|realtor-section|financial-section)', re.S)316_PHONE_RE = re.compile(r'\d{3}[\s ]\d{3}-\d{4}')317318# Libellés du tableau de caractéristiques, rendu « Libellé | Valeur » (le319# libellé PRÉCÈDE la valeur — vérifié sur les fiches live 2026-08 ; l'ancien320# ordre inverse ne captait que du bruit). Les plus spécifiques d'abord.321_DETAIL_LABELS = [322 "Type de propriété", "Genre de propriété", "Style de bâtiment",323 "Année de construction", "Nombre d'unités", "Superficie du bâtiment (au sol)",324 "Superficie du terrain", "Superficie habitable", "Dimensions du terrain",325 "Stationnement (total)", "Système de chauffage", "Mode de chauffage",326 "Énergie pour le chauffage", "Fenêtres", "Type de fenestration",327 "Fenestration", "Toiture", "Revêtement de la toiture", "Revêtement",328 "Sous-sol", "Piscine", "Garage", "Zonage", "Système d'égouts",329 "Approvisionnement en eau", "Déménagement", "Cuisine", "Armoires de cuisine",330 "Salle de bain / Salle d'eau", "Salle de bains",331 "Installation laveuse-sécheuse", "Eau (accès)", "Topographie", "Vue",332 "Particularités du site", "Allée", "Proximité",333 "Commodités de la propriété ou de l'unité", "Équipement disponible",334]335_DETAIL_LABELS_LOWER = {lb.lower() for lb in _DETAIL_LABELS}336# en-têtes de section : jamais des valeurs valides337_SECTION_HEADERS = {338 "particularités du bâtiment", "particularités du terrain",339 "détails des pièces", "détails financiers", "caractéristiques",340 "inclusions et exclusions", "dimensions", "niveau", "revêtement",341 "détails", "taxes", "total", "dans les environs",342 "calculatrice de versements hypothécaire", "note légale",343}344345346def _flatten(html: str) -> str:347 t = _html.unescape(re.sub(r'<[^>]+>', ' | ', html))348 t = re.sub(r'[ \t\r\n]*\|[ \t\r\n|]*', ' | ', t)349 return re.sub(r'[ \t]+', ' ', t)350351352def parse_remax_detail(html: str) -> dict:353 """Extrait TOUT le contenu d'une page détail RE/MAX : photos, description,354 coordonnées, caractéristiques complètes, pièces (dimensions), inclusions,355 taxes/évaluation, courtier. Objectif : rien perdre par rapport à la fiche source."""356 import json357 out: dict = {}358 details: dict = {}359360 # description via JSON-LD RealEstateListing361 for block in _LD_RE.findall(html):362 try:363 data = json.loads(block)364 except ValueError:365 continue366 for node in (data if isinstance(data, list) else [data]):367 if isinstance(node, dict) and node.get("@type") == "RealEstateListing" and node.get("description"):368 out["description"] = _html.unescape(node["description"]).strip()369370 # photos : toutes tailles → pleine résolution, dédoublonnées par nom de fichier371 seen, images = set(), []372 for u in _IMG_RE.findall(html):373 full = _IMG_SIZE_RE.sub("/www_full/", u)374 fn = full.rsplit("/", 1)[-1]375 if fn not in seen and "nophoto" not in full:376 seen.add(fn)377 images.append(full)378 if images:379 out["images"] = images380381 # coordonnées GPS (lien Google Maps)382 m = _COORD_RE.search(html)383 if m:384 out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))385386 # courtier + téléphone (le nom précède « Courtier immobilier »)387 mb = re.search(r'>\s*([A-ZÀ-Ÿ][A-Za-zÀ-ÿ .\'-]{4,45})\s*</span>[^<]*'388 r'(?:<[^>]+>\s*)*Courtier immobilier', html)389 if mb:390 name = _html.unescape(re.sub(r'\s+', ' ', mb.group(1))).strip()391 if name:392 out["broker_name"] = name393 mp = _PHONE_RE.search(html)394 if mp:395 out["broker_phone"] = mp.group(0)396397 # agence / bureau (« RE/MAX ALLIANCE INC. ») — pour les Sources par sous-agence398 ma = re.search(r'RE/MAX[^<,|"\n]{1,40}\bINC\.?', html)399 if ma:400 out["agency"] = _html.unescape(re.sub(r'\s+', ' ', ma.group(0))).strip().title() \401 .replace("Re/Max", "RE/MAX").replace("Inc.", "inc.")402403 text = _flatten(html)404405 # champs numériques principaux406 for field, rx in _SPEC_RE.items():407 m = rx.search(text)408 if m:409 out[field] = int(m.group(1))410 m = _AREA_RE.search(text)411 if m:412 out["area_sqft"] = parse_area_sqft(f"{m.group(1)} {m.group(2)}")413 m = _LOT_RE.search(text)414 if m:415 out["lot_sqft"] = parse_area_sqft(f"{m.group(1)} {m.group(2)}")416417 # tableau de caractéristiques complet (« Libellé | Valeur ») → details418 for label in _DETAIL_LABELS:419 m = re.search(re.escape(label) + r'\s*\|\s*([^|]{1,60})', text)420 if m:421 val = re.sub(r'\s+', ' ', m.group(1)).strip(" |")422 low = val.lower().strip(" :")423 # garde-fou : un champ vide fait suivre le libellé voisin ou424 # l'en-tête de section — on ne capte jamais ces « valeurs »425 if (val and 1 <= len(val) <= 60 and low != label.lower()426 and low not in _DETAIL_LABELS_LOWER427 and low not in _SECTION_HEADERS):428 details[label] = val429430 # « Détails financiers » : taxes municipales/scolaires + évaluation municipale431 fin_at = text.find("Détails financiers")432 fin = text[fin_at: fin_at + 900] if fin_at >= 0 else ""433 if fin:434 def _amount(m) -> str:435 return re.sub(r'[\s ]+', ' ', m.group(m.lastindex)).strip()436 m = _FIN_TAX_MUNI_RE.search(fin)437 if m:438 details["Taxes municipales"] = _amount(m) + \439 (f" ({m.group(1)})" if m.group(1) else "")440 m = _FIN_TAX_SCOL_RE.search(fin)441 if m:442 details["Taxes scolaires"] = _amount(m) + \443 (f" ({m.group(1)})" if m.group(1) else "")444 m = _FIN_EVAL_LAND_RE.search(fin)445 if m:446 details["Évaluation municipale (terrain)"] = _amount(m)447 m = _FIN_EVAL_BLDG_RE.search(fin)448 if m:449 details["Évaluation municipale (bâtiment)"] = _amount(m)450 m = _FIN_EVAL_YEAR_RE.search(fin)451 if m:452 details["Évaluation municipale (année)"] = m.group(1)453454 # pièces avec dimensions/niveau/revêtement455 rooms = []456 for blk in _ROOM_RE.findall(html):457 rt = _html.unescape(re.sub(r'<[^>]+>', ' ', blk))458 rt = re.sub(r'\s+', ' ', rt).strip()459 name = re.split(r'Niveau\s*:', rt)[0].strip()460 niveau = (re.search(r'Niveau\s*:\s*([^:]+?)(?:Dimensions|Revêtement|$)', rt) or [None, ""])461 dim = re.search(r'Dimensions\s*:\s*([0-9\'".,X x×]+)', rt)462 rev = re.search(r'Revêtement\s*:\s*([A-Za-zÀ-ÿ ,-]+?)(?:\s*Détails|\s*$)', rt)463 if name:464 rooms.append({465 "nom": name[:40],466 "niveau": (niveau[1].strip() if niveau else ""),467 "dimensions": (dim.group(1).strip() if dim else ""),468 "revetement": (rev.group(1).strip() if rev else ""),469 })470 if rooms:471 details["pieces"] = rooms[:20]472473 # quick stats (Nb de pièces, superficie…)474 for label, val in _QSTAT_RE.findall(html):475 label = _html.unescape(re.sub(r'\s+', ' ', label)).strip()476 val = _html.unescape(re.sub(r'\s+', ' ', val)).strip()477 if label and val and label not in details:478 details[label] = val479480 # inclusions / exclusions → features481 mi = _INCL_RE.search(html)482 feats = []483 if mi:484 blk = _html.unescape(re.sub(r'<[^>]+>', '\n', mi.group(1)))485 for line in blk.split('\n'):486 line = line.strip(" \t•-")487 if 3 <= len(line) <= 120 and not line.lower().startswith(("inclusion", "exclusion")):488 feats.append(line)489 if feats:490 out["features"] = feats[:25]491492 # superficie habitable depuis details si pas déjà captée493 if out.get("area_sqft") is None and details.get("Superficie habitable"):494 out["area_sqft"] = parse_area_sqft(details["Superficie habitable"])495 if out.get("lot_sqft") is None and details.get("Superficie du terrain"):496 out["lot_sqft"] = parse_area_sqft(details["Superficie du terrain"])497498 if details:499 out["details"] = details500 return out501502503def _apply_detail(lst: PropertyListing, d: dict) -> None:504 if not d:505 return506 if d.get("images"):507 lst.images = d["images"]508 if d.get("features"):509 lst.features = d["features"]510 if d.get("details"):511 lst.details.update(d["details"])512 # le nom réel du courtier (page détail) remplace le placeholder « RE/MAX Québec »513 if d.get("broker_name"):514 lst.broker_name = d["broker_name"]515 # agence/bureau -> sous-agence pour les Sources516 if d.get("agency"):517 lst.agency = d["agency"]518 for f in ("description", "bedrooms", "bathrooms", "powder_rooms",519 "year_built", "area_sqft", "lot_sqft", "lat", "lng",520 "broker_phone"):521 if d.get(f) is not None and getattr(lst, f, None) in (None, "", 0):522 setattr(lst, f, d[f])523524525def _from_slug(slug: str) -> tuple[str, str]:526 """slug « maison-a-vendre-laurentides/1744-rue-carmen-val-david-9004907 »527 -> (type de propriété, région)."""528 if not slug:529 return "", ""530 head = slug.split("/", 1)[0] # maison-a-vendre-laurentides531 prop_type = ""532 for key, canon in _TYPE_SLUG.items():533 if re.search(rf"\b{key}", head):534 prop_type = canon535 break536 # région = ce qui suit « -a-vendre-/-for-sale- »537 m = re.search(r"(?:a-vendre|for-sale)-(.+)$", head)538 region = m.group(1).replace("-", " ").title() if m else ""539 return prop_type, region540