Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/realtypress.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-2713# Last Modified : 2026-08-2714#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 (Québec + Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/realtypress.py : connecteur GÉNÉRIQUE RealtyPress (Ontario)91# RealtyPress = plugin WordPress branché sur le flux CREA DDF ; ~35 sites92# d'agences/équipes ontariennes confirmés (recensement 2026-08-27, voir93# docs/ontario-agences-connecteurs.md). Chaque site expose l'IDX/DDF complet94# de son board (OREB, ITSO, KAREA…) en HTML server-rendered, sans anti-bot :95# un seul parseur couvre quasi toute la province.96#97# - liste : archive /listing/page/N/?posts_per_page=100 (100 cartes/page ;98# ⚠ ?posts_per_page directement sur /listing = 301/vide) ; cartes99# class="rps-property-result" (ruban For sale/For rent, prix, adresse,100# ville, caractéristiques) ;101# - fiche : mur CREA « I Accept The Terms » contourné par le cookie102# `disclaimer=accepted` ; tableaux <strong>Label</strong>/valeur (MLS®103# Number, Property Type, Bedrooms…), description « … (id:NNNNN) »,104# lat/lng JSON-LD, photos ddfcdn.realtor.ca ;105# - external_id = ddf<id> (préfixe : jamais de collision avec les n° Centris106# QC) ; sources avec infixe _ag_ → la dédup par external_id masque les107# doublons inter-sites (le même bien DDF publié sur plusieurs sites).108# Sites générés depuis data/ontario_agencies.json (un source_id par site).109# -----------------------------------------------------------------------------110from __future__ import annotations111112import html as _html113import json114import os115import re116import urllib.parse117from pathlib import Path118119from .base import BaseConnector120from . import _detailutil as du121from ..schema import PropertyListing122123REGISTRY = Path(__file__).resolve().parent.parent.parent / "data" / "ontario_agencies.json"124DETAIL_LIMIT = int(os.environ.get("IMMOKA_RP_DETAIL_LIMIT",125 os.environ.get("IMMOKA_DETAIL_LIMIT", "150")))126127_CARD_RE = re.compile(r'<div class="rps-property-result">')128# fiche = 1er lien de la carte finissant par -<id DDF>/ ; le chemin varie selon129# le site (/listing/, /listings/, /all-regional-listings/…)130_LINK_RE = re.compile(r'href="(https?://[^"]+?-(\d{6,10})/?)"')131_RIBBON_RE = re.compile(r'rps-ribbon[^>]*>\s*([^<]+?)\s*<')132_PRICE_RE = re.compile(r'rps-price[^>]*>\s*\$\s*([\d,]+)')133_H4_RE = re.compile(r"<h4>\s*(.*?)\s*</h4>", re.S)134# avec ou sans <strong> selon le thème du site135_CITY_RE = re.compile(r'city-province-postalcode[^>]*>\s*(?:<strong>\s*)?([^<]+?)\s*<', re.S)136_FEAT_RE = re.compile(r'rps-result-feature-label[^>]*>\s*([^<]+?)\s*<')137_CARD_BROKER_RE = re.compile(r'text-muted[^>]*>\s*<small>\s*([^<]+?)\s*(?:<br|</small>)', re.S)138_DDFIMG_RE = re.compile(r'https://ddfcdn\.realtor\.ca/[^")\'\s\\]+')139_ROW_RE = re.compile(r"<td[^>]*>\s*<strong>([^<]{2,45})</strong>\s*</td>\s*"140 r"<td[^>]*>(.*?)</td>", re.S)141_DESC_RE = re.compile(r'<!--\s*Description\s*-->\s*<p[^>]*>(.*?)</p>', re.S)142_DESC_RE2 = re.compile(r'<p itemprop="description"[^>]*>(.*?)</p>', re.S)143# ville depuis <title> « 3383 Romeo Street, Greater Sudbury (Valley East), Ontario … »144_TITLE_CITY_RE = re.compile(r",\s*([^,<>|]{2,60}),\s*Ontario\b")145_PRICING_RE = re.compile(r'rps-pricing[^>]*>\s*\$\s*([\d,]+)')146_ID_TAIL_RE = re.compile(r"\s*\(id:\d{4,9}\)\s*$")147_TAG_RE = re.compile(r"<[^>]+>")148_NUM_RE = re.compile(r"[\d,]+(?:\.\d+)?")149_YEAR_RE = re.compile(r"\b(1[6-9]\d{2}|20\d{2})\b")150# territoire couvert (Québec + Ontario) — même boîte que schema.finalize()151_BBOX = (41.6, 63.0, -95.5, -56.0)152153154def _num(s: str) -> float | None:155 m = _NUM_RE.search(s or "")156 if not m:157 return None158 try:159 return float(m.group(0).replace(",", ""))160 except ValueError:161 return None162163164class _RealtyPress(BaseConnector):165 """Connecteur générique de site RealtyPress (voir data/ontario_agencies.json)."""166167 agency_name = ""168 site_url = ""169 archive = "listing" # chemin de l'archive (revelrealty: "listings",170 # codygroup: "all-regional-listings")171 max_pages = 150 # 100 cartes/page → jusqu'à 15 000 fiches par site172 request_delay = 0.6173174 def fetch(self) -> list[PropertyListing]:175 # mur CREA des fiches détail : le cookie suffit (posé pour tout domaine,176 # les redirections www/apex restent couvertes)177 self.session.cookies.set("disclaimer", "accepted")178 by_id: dict[str, PropertyListing] = {}179 base = self.site_url.rstrip("/")180 dry = 0181 for page in range(1, self.max_pages + 1):182 url = f"{base}/{self.archive}/page/{page}/?posts_per_page=100"183 try:184 body = self.get(url).text185 except Exception:186 break187 cards = self._cards(body)188 if not cards:189 break190 before = len(by_id)191 for card in cards:192 self._parse_card(card, by_id)193 dry = dry + 1 if len(by_id) == before else 0194 if dry >= 2:195 break196 listings = list(by_id.values())197 du.enrich(self, listings, DETAIL_LIMIT, parse_rp_detail, key="v1")198 for lst in listings:199 # n° MLS du board (fiche détail) — utile à la dédup inter-plateformes200 if not lst.mls and lst.details.get("MLS® Number"):201 lst.mls = str(lst.details["MLS® Number"])202 if not lst.title:203 lst.title = ", ".join(filter(None, (lst.address, lst.city))) \204 or "Propriété à vendre"205 return listings206207 def _cards(self, body: str) -> list[str]:208 marks = list(_CARD_RE.finditer(body))209 return [body[m.start():(marks[i + 1].start() if i + 1 < len(marks)210 else m.start() + 6000)]211 for i, m in enumerate(marks)]212213 def _parse_card(self, card: str, by_id: dict) -> None:214 ml = _LINK_RE.search(card)215 if not ml:216 return217 url, ddf = ml.group(1), ml.group(2)218 eid = f"ddf{ddf}"219 if eid in by_id:220 return221 mr = _RIBBON_RE.search(card)222 ribbon = (mr.group(1) if mr else "").strip().lower()223 if "rent" in ribbon or "lease" in ribbon:224 return # locations : hors périmètre225 lst = PropertyListing(source=self.source_id, external_id=eid, url=url,226 region="Ontario", agency=self.agency_name,227 broker_name=self.agency_name)228 ma = _H4_RE.search(card)229 if ma:230 lst.address = _html.unescape(_TAG_RE.sub(" ", ma.group(1))).strip()231 mc = _CITY_RE.search(card)232 if mc:233 city = _html.unescape(mc.group(1)).strip().rstrip(",")234 city = re.sub(r",?\s*Ontario\b.*$", "", city, flags=re.I)235 lst.city = city.split("(")[0].strip()236 mp = _PRICE_RE.search(card)237 if mp:238 lst.price = _num(mp.group(1))239 lst.price_label = f"{mp.group(1)} $"240 for feat in _FEAT_RE.findall(card):241 f = _html.unescape(feat).strip()242 low = f.lower()243 n = _num(f)244 if not n:245 continue246 if "bedroom" in low:247 lst.bedrooms = int(n)248 elif "bathroom" in low:249 lst.bathrooms = int(n)250 elif "sqft" in low or "sq ft" in low or "ft" in low:251 lst.area_sqft = n # plage « 1,100 - 1,500 ft² » : borne basse252 mbk = _CARD_BROKER_RE.search(card)253 if mbk:254 lst.broker_name = _html.unescape(mbk.group(1)).strip()[:120]255 mi = _DDFIMG_RE.search(card)256 if mi:257 lst.images = [mi.group(0)]258 by_id[lst.external_id] = lst259260261def parse_rp_detail(html: str) -> dict:262 """Fiche RealtyPress : tableaux DDF, description, GPS, galerie, courtier."""263 out: dict = {}264 details: dict = {}265266 for lab, val in _ROW_RE.findall(html):267 label = _html.unescape(lab).strip().rstrip(":")268 value = re.sub(r"\s+", " ", _html.unescape(_TAG_RE.sub(" ", val))).strip()269 if label and value and len(value) <= 300:270 details.setdefault(label, value)271272 def dv(*labels: str) -> str:273 for lb in labels:274 if details.get(lb):275 return details[lb]276 return ""277278 b = _num(dv("Bedrooms Total", "Bedrooms", "Bedrooms Above Ground"))279 if b is not None and 0 < b <= 30:280 out["bedrooms"] = int(b)281 b = _num(dv("Bathroom Total", "Bathrooms"))282 if b is not None and 0 < b <= 30:283 out["bathrooms"] = int(b)284 b = _num(dv("Half Bath Total"))285 if b is not None and 0 < b <= 10:286 out["powder_rooms"] = int(b)287 my = _YEAR_RE.search(dv("Constructed Date", "Construction Year", "Age"))288 if my:289 out["year_built"] = int(my.group(1))290 si = dv("Size Interior")291 if si and "sqft" in si.lower().replace(" ", ""):292 a = _num(si) # « 7,901 Sqft » / « 1200 - 1399 sqft »293 if a and a >= 100:294 out["area_sqft"] = a295 pt = dv("Property Type", "Building Type", "Type")296 if pt:297 out["property_type"] = pt # anglais DDF — normalisé par finalize()298 sec = dv("Neigbourhood", "Neighbourhood", "Community Name")299 if sec:300 out["sector"] = sec301302 mp = _PRICING_RE.search(html)303 if mp:304 out["price"] = _num(mp.group(1))305 out["price_label"] = f"{mp.group(1)} $"306307 md = _DESC_RE.search(html) or _DESC_RE2.search(html)308 if md:309 desc = _html.unescape(_TAG_RE.sub(" ", md.group(1)))310 desc = re.sub(r"\s+", " ", desc).strip()311 out["description"] = _ID_TAIL_RE.sub("", desc)[:6000]312313 mt = re.search(r"<title>(.*?)</title>", html, re.S)314 if mt:315 mc = _TITLE_CITY_RE.search(_html.unescape(mt.group(1)))316 if mc:317 # « Greater Sudbury (Valley East) » : le secteur part dans sector318 city = mc.group(1).split("(")[0].strip()319 if city and not any(c.isdigit() for c in city):320 out["city"] = city321 msec = re.search(r"\(([^)]{2,45})\)", mc.group(1))322 if msec and "sector" not in out:323 out["sector"] = msec.group(1).strip()324325 for n in du.ld_nodes(html):326 t = n.get("@type")327 types = set(t if isinstance(t, list) else [t])328 geo = n.get("geo") or {}329 if isinstance(geo, dict) and "lat" not in out:330 try:331 lat, lng = float(geo["latitude"]), float(geo["longitude"])332 if _BBOX[0] <= lat <= _BBOX[1] and _BBOX[2] <= lng <= _BBOX[3]:333 out["lat"], out["lng"] = lat, lng334 except (KeyError, TypeError, ValueError):335 pass336 if types & {"RealEstateAgent", "Organization"}:337 name = str(n.get("name") or "").strip()338 if name and "broker_name" not in out:339 out["broker_name"] = name[:120]340 tel = str(n.get("telephone") or "").strip()341 if tel and "broker_phone" not in out:342 out["broker_phone"] = tel[:40]343 if "lat" not in out:344 m = re.search(r'"latitude"\s*:\s*"?(-?\d{1,2}\.\d{3,})"?\s*,\s*'345 r'"longitude"\s*:\s*"?(-?\d{2,3}\.\d{3,})"?', html)346 if m:347 lat, lng = float(m.group(1)), float(m.group(2))348 if _BBOX[0] <= lat <= _BBOX[1] and _BBOX[2] <= lng <= _BBOX[3]:349 out["lat"], out["lng"] = lat, lng350351 gal = [u for u in dict.fromkeys(_DDFIMG_RE.findall(html))352 if "/listings/" in u.lower()]353 if gal:354 out["images"] = gal[:60]355356 if details:357 out["details"] = details358 return out359360361def _load() -> list[dict]:362 try:363 return json.loads(REGISTRY.read_text(encoding="utf-8"))364 except Exception:365 return []366367368# PAUSE ONTARIO (2026-08-27) : l'expansion ON est suspendue — les classes ne369# s'enregistrent dans le registre CONNECTORS que si IMMOKA_ONTARIO=1 est posé370# (.env). Les annonces déjà en base sont conservées mais dépubliées par371# quality.refresh (raison « pause-ontario »). Rien n'est effacé.372_ONTARIO = os.environ.get("IMMOKA_ONTARIO") == "1"373374# Génère une classe par site du registre.375for _ag in (_load() if _ONTARIO else []):376 if not all(_ag.get(k) for k in ("id", "site")):377 continue378 _sid = _ag["id"]379 globals()[f"REALTYPRESS_{_sid.upper()}"] = type(380 "RealtyPress" + "".join(p.title() for p in _sid.split("_")),381 (_RealtyPress,),382 {383 "source_id": _sid,384 "site_url": _ag["site"],385 "agency_name": _ag.get("name", _sid),386 "archive": _ag.get("archive", "listing"),387 "max_pages": int(_ag.get("max_pages", 150)),388 },389 )390