Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/realtor_ca.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1813# Last Modified : 2026-09-1314#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/realtor_ca.py : Realtor.ca (couverture MLS pan-bannières, QC)91# API interne https://api2.realtor.ca/Listing.svc/PropertySearch_Post (POST92# form). Protégée (DataDome/Incapsula) : l'accès direct renvoie 403, mais93# l'API se REJOUE via Scrapfly ASP SANS render_js (1 crédit-appel ASP, pas de94# navigateur) → JSON complet : n° MLS, GPS, prix, CAC/SDB, superficie, photos,95# courtier + agence. Vérifié 2026-08-18 : 200 fiches/page, plafond serveur96# 600 fiches (MaxRecords) par recherche → SHARDING par boîtes lat/lng97# couvrant le Québec, tri « plus récentes d'abord » (Sort=6-D).98#99# BUDGET BORNÉ : IMMOKA_REALTOR_MAX fiches max par sync (défaut 2 000, soit100# ~10 appels Scrapfly), réparties en balayant la page 1 de chaque shard puis101# les pages 2-3 si le budget le permet. Les fiches plus anciennes sortent de102# la fenêtre au fil des syncs (miss_count → active=0) : le connecteur vaut103# surtout pour les inscriptions récentes des bannières non couvertes.104# Mettre IMMOKA_REALTOR_MAX=0 pour désactiver le connecteur.105#106# source_id « realtor_ag_ca » : l'infixe _ag_ + external_id = n° MLS Centris107# activent la dédup existante — toute fiche déjà couverte par un connecteur108# direct (RE/MAX, Royal LePage, Sutton…) est masquée, seules les fiches109# UNIQUES (petites bannières sans connecteur) restent visibles.110#111# ENRICHISSEMENT DÉTAIL (2026-08-18) : la réponse PropertySearch_Post ne112# contient qu'UNE photo et un PublicRemarks VIDE (vérifié) — la galerie113# complète, la description et les caractéristiques Building/Land viennent de114# l'API Listing.svc/PropertyDetails (GET, mêmes protections → Scrapfly ASP115# sans render_js, 1 crédit-appel), rejouée avec CultureId=2 (français) via116# ReferenceNumber=<MLS> + PropertyID=<Id interne>. Cache BD detail_cache117# (_detailutil.enrich) : chaque fiche n'est détaillée qu'UNE fois ; budget118# IMMOKA_REALTOR_DETAIL_LIMIT appels/cycle (défaut 100, override ponctuel119# IMMOKA_DETAIL_LIMIT) → rattrapage progressif du stock, nouveautés ensuite.120# -----------------------------------------------------------------------------121from __future__ import annotations122123import json124import os125import time126127import requests128129from . import _detailutil as du130from .base import BaseConnector131from ..schema import PropertyListing132133SEARCH_URL = "https://api2.realtor.ca/Listing.svc/PropertySearch_Post"134DETAIL_URL = "https://api2.realtor.ca/Listing.svc/PropertyDetails"135SITE = "https://www.realtor.ca"136137MAX_RECORDS = int(os.environ.get("IMMOKA_REALTOR_MAX", "2000"))138DETAIL_LIMIT = int(os.environ.get("IMMOKA_DETAIL_LIMIT")139 or os.environ.get("IMMOKA_REALTOR_DETAIL_LIMIT", "100"))140PER_PAGE = 200 # maximum accepté par l'API141MAX_PAGES_PER_SHARD = 3 # plafond serveur : MaxRecords=600 par recherche142143# Boîtes (sud, ouest, nord, est) couvrant le Québec habité, par densité144# décroissante — le budget est d'abord dépensé sur les marchés actifs.145SHARDS: list[tuple[str, float, float, float, float]] = [146 ("montreal-laval", 45.35, -74.05, 45.75, -73.30),147 ("monteregie", 45.00, -74.40, 45.35, -72.80),148 ("rive-sud-est", 45.35, -73.30, 45.75, -72.80),149 ("laurentides-lanaudiere", 45.75, -74.80, 46.40, -73.20),150 ("quebec-metro", 46.55, -71.65, 47.10, -70.90),151 ("chaudiere-appalaches", 46.00, -71.80, 46.85, -70.00),152 ("estrie", 45.00, -72.80, 45.90, -71.50),153 ("mauricie-cdq", 45.90, -73.20, 46.90, -71.80),154 ("outaouais", 45.30, -77.60, 46.50, -74.80),155 ("saguenay-lac-st-jean", 48.00, -72.60, 48.80, -70.70),156 ("bas-st-laurent-gaspesie", 47.20, -70.60, 49.40, -64.00),157 ("charlevoix-cote-nord", 47.00, -71.00, 50.40, -65.90),158 ("abitibi-temiscamingue", 47.20, -79.60, 48.90, -77.40),159 ("hautes-laurentides", 46.40, -76.00, 47.20, -74.20),160]161162163class RealtorCaConnector(BaseConnector):164 source_id = "realtor_ag_ca"165 request_delay = 0.2 # Scrapfly gère la politesse côté cible166 use_detail_cache = True # galerie/description via PropertyDetails, cachées167168 def __init__(self) -> None:169 super().__init__()170 # external_id -> Id interne Realtor (PropertyID requis par l'API détail)171 self._prop_ids: dict[str, str] = {}172173 def scrapfly(self, url: str, **kw) -> dict:174 # Coupures réseau transitoires vers api.scrapfly.io (ConnectTimeout175 # 180 s observé 2×, 2026-09-13) : sans retentative, un seul raté tue176 # les ~11 appels du sync → 0 fiche. On retente avec pause avant177 # de laisser l'exception remonter.178 last: Exception | None = None179 for attempt in range(3):180 try:181 return super().scrapfly(url, **kw)182 except (requests.ConnectionError, requests.Timeout) as exc:183 last = exc184 if attempt < 2:185 time.sleep(20 * (attempt + 1))186 raise last # type: ignore[misc]187188 def _search(self, shard: tuple, page: int) -> dict:189 _, south, west, north, east = shard190 body = "&".join(f"{k}={v}" for k, v in {191 "ZoomLevel": 10,192 "LatitudeMax": north, "LongitudeMax": east,193 "LatitudeMin": south, "LongitudeMin": west,194 "Sort": "6-D", # inscription la plus récente d'abord195 "PropertyTypeGroupID": 1, # résidentiel196 "TransactionTypeId": 2, # à vendre197 "PropertySearchTypeId": 0,198 "Currency": "CAD",199 "RecordsPerPage": PER_PAGE,200 "CurrentPage": page,201 "CultureId": 1,202 "ApplicationId": 1,203 "PropertyStatusId": 1,204 "Version": "7.0",205 }.items())206 result = self.scrapfly(207 SEARCH_URL, render_js=False, asp=True, method="POST", body=body,208 headers={209 "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",210 "Referer": "https://www.realtor.ca/",211 "Origin": "https://www.realtor.ca",212 })213 try:214 return json.loads(result.get("content") or "")215 except ValueError:216 return {}217218 def fetch(self) -> list[PropertyListing]:219 if MAX_RECORDS <= 0:220 return []221 by_id: dict[str, PropertyListing] = {}222 exhausted: set[str] = set()223 for page in range(1, MAX_PAGES_PER_SHARD + 1):224 for shard in SHARDS:225 name = shard[0]226 if name in exhausted or len(by_id) >= MAX_RECORDS:227 continue228 data = self._search(shard, page)229 results = data.get("Results") or []230 if len(results) < PER_PAGE:231 exhausted.add(name)232 if not results:233 continue234 for item in results:235 lst = self._to_listing(item)236 if lst and lst.external_id not in by_id:237 by_id[lst.external_id] = lst238 if len(by_id) >= MAX_RECORDS:239 break240 listings = list(by_id.values())241 self._enrich(listings)242 return listings243244 # -- détail : galerie complète + description + caractéristiques -----------245 def _fetch_detail(self, mls: str, pid: str) -> str:246 """JSON brut de l'API PropertyDetails (CultureId=2 → contenu français)."""247 result = self.scrapfly(248 f"{DETAIL_URL}?ReferenceNumber={mls}&PropertyID={pid}"249 "&ApplicationId=1&CultureId=2&PreferedMeasurementUnit=1",250 render_js=False, asp=True,251 headers={"Referer": "https://www.realtor.ca/",252 "Origin": "https://www.realtor.ca"})253 if result.get("status_code") != 200:254 raise RuntimeError(f"PropertyDetails {mls}: "255 f"HTTP {result.get('status_code')}")256 return result.get("content") or ""257258 def _enrich(self, listings: list[PropertyListing]) -> None:259 """Complète chaque fiche via PropertyDetails, avec cache BD + budget.260261 Contrairement à _detailutil.enrich, un échec (challenge ASP, JSON262 invalide) n'est JAMAIS mis en cache : la fiche est retentée au263 prochain cycle. Une fiche détaillée avec succès ne coûte plus rien.264 """265 if DETAIL_LIMIT <= 0:266 return267 from .. import db268 con = db.connect()269 budget = DETAIL_LIMIT270 try:271 for lst in listings:272 payload = db.get_cached_detail(con, self.source_id,273 lst.external_id, "v1")274 if payload is None:275 pid = self._prop_ids.get(lst.external_id, "")276 mls = lst.mls or lst.external_id277 if budget <= 0 or not pid or not mls:278 continue279 budget -= 1280 try:281 payload = _parse_detail(self._fetch_detail(mls, pid))282 except Exception:283 payload = {}284 if not payload:285 continue # échec transitoire : nouvel essai plus tard286 db.put_cached_detail(con, self.source_id,287 lst.external_id, "v1", payload)288 du.apply_detail(lst, payload)289 finally:290 con.close()291292 def _to_listing(self, item: dict) -> PropertyListing | None:293 prop = item.get("Property") or {}294 addr = prop.get("Address") or {}295 text = addr.get("AddressText") or ""296 # « 680 Rue De Courcelle|#613|Montréal (Le Sud-Ouest), Quebec H4C0B8 »297 if ", Quebec" not in text and ", Québec" not in text:298 return None # les shards frontaliers débordent (Ottawa, N.-B.)299 parts = [p.strip() for p in text.split("|")]300 locality = parts[-1] if parts else ""301 street = ", ".join(parts[:-1]) if len(parts) > 1 else ""302 city = sector = ""303 loc = locality.split(", Quebec")[0].split(", Québec")[0]304 if "(" in loc:305 city, _, rest = loc.partition("(")306 city, sector = city.strip(), rest.rstrip(")").strip()307 else:308 city = loc.strip()309 mls = str(item.get("MlsNumber") or "").strip()310 rid = str(item.get("Id") or "").strip()311 if not (mls or rid) or not street:312 return None313 try:314 price = float(prop.get("PriceUnformattedValue"))315 except (TypeError, ValueError):316 price = None317 building = item.get("Building") or {}318 lst = PropertyListing(319 source=self.source_id,320 external_id=mls or rid,321 url=f"{SITE}{item.get('RelativeDetailsURL') or ''}",322 title=f"{building.get('Type') or prop.get('Type') or ''} — {city}".strip(" —"),323 address=street,324 sector=sector,325 city=city,326 property_type=building.get("Type") or prop.get("Type") or "",327 price=price,328 price_label=prop.get("Price") or "",329 mls=mls,330 description=(item.get("PublicRemarks") or "").strip(),331 )332 try:333 lst.lat = float(addr.get("Latitude"))334 lst.lng = float(addr.get("Longitude"))335 except (TypeError, ValueError):336 pass337 beds = str(building.get("Bedrooms") or "")338 if beds:339 try: # « 3 + 1 » → 4340 lst.bedrooms = sum(int(x) for x in beds.replace(" ", "").split("+") if x)341 except ValueError:342 pass343 try:344 lst.bathrooms = int(building.get("BathroomTotal"))345 except (TypeError, ValueError):346 pass347 try:348 lst.powder_rooms = int(building.get("HalfBathTotal"))349 except (TypeError, ValueError):350 pass351 size = building.get("SizeInterior") or ""352 if size:353 lst.details["Superficie habitable"] = size354 land = (item.get("Land") or {}).get("SizeTotal") or ""355 if land:356 lst.details["Superficie du terrain"] = land357 alt = (item.get("AlternateURL") or {}).get("DetailsLink") or ""358 if alt:359 lst.details["Annonce originale"] = alt360 lst.images = [p.get("HighResPath") or p.get("MedResPath")361 for p in (prop.get("Photo") or []) if isinstance(p, dict)]362 lst.images = [u for u in lst.images if u]363 ind = (item.get("Individual") or [{}])[0]364 lst.broker_name = ind.get("Name") or ""365 org = ind.get("Organization") or {}366 lst.agency = org.get("Name") or ""367 phones = ind.get("Phones") or []368 if phones:369 p0 = phones[0]370 lst.broker_phone = f"{p0.get('AreaCode', '')} {p0.get('PhoneNumber', '')}".strip()371 if rid: # Id interne Realtor, requis par l'API PropertyDetails372 self._prop_ids[lst.external_id] = rid373 return lst374375376# libellés français des caractéristiques structurées de PropertyDetails377_DETAIL_LABELS = [378 # (section, clé API, libellé Immo-Ka)379 ("Building", "ConstructedDate", "Année de construction"),380 ("Building", "SizeInterior", "Superficie habitable"),381 ("Building", "StoriesTotal", "Nombre d'étages"),382 ("Building", "ConstructionStyleAttachment", "Type de bâtiment"),383 ("Building", "HeatingType", "Système de chauffage"),384 ("Building", "HeatingFuel", "Énergie pour le chauffage"),385 ("Building", "CoolingType", "Climatisation"),386 ("Building", "ExteriorFinish", "Revêtement"),387 ("Building", "RoofMaterial", "Toiture"),388 ("Building", "FoundationType", "Fondations"),389 ("Building", "BasementType", "Sous-sol"),390 ("Building", "FireplaceTotal", "Foyers"),391 ("Building", "Water", "Approvisionnement en eau"),392 ("Land", "SizeTotal", "Superficie du terrain"),393 ("Land", "Sewer", "Système d'égouts"),394 ("Land", "LandscapeFeatures", "Aménagement paysager"),395 ("Property", "PoolType", "Piscine"),396 ("Property", "ZoningType", "Zonage"),397 ("Property", "ParkingSpaceTotal", "Stationnement (total)"),398 ("Property", "OwnershipType", "Type de copropriété"),399 ("Property", "TaxTotal", "Taxes annuelles"),400]401402403def _parse_detail(content: str) -> dict:404 """Réponse PropertyDetails (JSON) → payload compatible du.apply_detail."""405 try:406 d = json.loads(content or "")407 except ValueError:408 return {}409 if not isinstance(d, dict) or not d.get("Id"):410 return {}411 prop = d.get("Property") or {}412 sections = {"Property": prop, "Building": d.get("Building") or {},413 "Land": d.get("Land") or {}}414 out: dict = {}415 images = [p.get("HighResPath") or p.get("MedResPath")416 for p in (prop.get("Photo") or []) if isinstance(p, dict)]417 images = [u for u in images if u]418 if images:419 out["images"] = images420 desc = (d.get("PublicRemarks") or "").strip()421 if desc:422 out["description"] = desc423 details: dict = {}424 for section, key, label in _DETAIL_LABELS:425 val = sections[section].get(key)426 if val not in (None, "", 0, "0"):427 details[label] = str(val)428 parking = [p.get("Name") for p in (prop.get("Parking") or [])429 if isinstance(p, dict) and p.get("Name")]430 if parking:431 details["Stationnement"] = ", ".join(dict.fromkeys(parking))432 rooms = (sections["Building"].get("Room") or [])433 if rooms:434 details["Nombre de pièces"] = str(len(rooms))435 alt = (d.get("AlternateURL") or {}).get("DetailsLink") or ""436 if alt:437 details["Annonce originale"] = alt438 if details:439 out["details"] = details440 feats: list[str] = []441 for blob in (prop.get("Features"), prop.get("AmmenitiesNearBy")):442 for f in (blob or "").split(","):443 if f.strip():444 feats.append(f.strip())445 if feats:446 out["features"] = feats447 b = sections["Building"]448 for src, dst in (("ConstructedDate", "year_built"),449 ("HalfBathTotal", "powder_rooms")):450 v = du._int(b.get(src))451 if v:452 out[dst] = v453 ind = (d.get("Individual") or [{}])[0]454 if ind.get("Name"):455 out["broker_name"] = ind["Name"]456 for p in ind.get("Phones") or []:457 if p.get("PhoneNumber"):458 out["broker_phone"] = (f"{p.get('AreaCode', '')} "459 f"{p['PhoneNumber']}").strip()460 break461 return out462