Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/realstar.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# 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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/realstar.py : connecteur Realstar (realstar.ca)91# Site protégé par Cloudflare (403 pour les robots) et rendu côté client92# (moteur RentCafe/Yardi) : tout passe par le rendu Scrapfly avec attente (ex-Firecrawl).93# 1) /searchlisting?province=Quebec -> cartes propriétés (nom, adresse,94# lits/sdb/pi², fourchette de prix, téléphone, vignette) ;95# 2) fiche de chaque propriété couverte (Grand Montréal, Gatineau,96# Sherbrooke) -> galerie photos, description, points forts ;97# 3) fiche /floorplans -> plans structurés (type, chambres, pi², prix,98# nombre d'unités disponibles) — disponibilité et prix réels.99# Une annonce par propriété (uid stables). Les pages détail passent par100# self.detail(...) (cache BD) : le rendu n'est rappelé que si la carte101# liste a changé.102# Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : quand LOUKA_ONTARIO=1,103# un rendu supplémentaire de ?province=Ontario alimente les cartes104# /apartments/on/ des 7 régions couvertes (Toronto/GTA, Ottawa, Hamilton,105# Kitchener-Waterloo, London, Cobourg), avec plafonds propriétés/rendus106# SÉPARÉS (le budget QC n'est jamais entamé). Sans la variable,107# comportement strictement identique (QC seulement).108# -----------------------------------------------------------------------------109from __future__ import annotations110111import hashlib112import os113import re114115from bs4 import BeautifulSoup116117from ..schema import Listing, parse_price118from .base import BaseConnector119120# Expansion Ontario 2026-08 — gate d'environnement (défaut : QC seulement)121_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"122123SEARCH_URL = "https://www.realstar.ca/searchlisting?province=Quebec"124ON_SEARCH_URL = "https://www.realstar.ca/searchlisting?province=Ontario"125126# Ville du chemin /apartments/qc/<ville>/<slug> -> (ville affichée, secteur)127_GM_CITIES = {128 "montreal": ("Montréal", ""),129 "cote-saint-luc": ("Côte-Saint-Luc", ""),130 "brossard": ("Brossard", ""),131 "pointe-claire": ("Pointe-Claire", ""),132 "boisbriand": ("Boisbriand", ""), # Rive-Nord proche133 "sainte-therese": ("Sainte-Thérèse", ""), # Rive-Nord proche134 "laval": ("Laval", ""),135 "longueuil": ("Longueuil", ""),136 # Expansion provinciale (2026-08)137 "gatineau": ("Gatineau", ""),138 "hull": ("Gatineau", "Hull"),139 "sherbrooke": ("Sherbrooke", ""),140}141142# Ville du chemin /apartments/on/<ville>/<slug> -> (ville affichée, secteur).143# Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : 7 régions (Toronto/GTA,144# Ottawa, Hamilton, Kitchener-Waterloo, London, Cobourg).145_ON_CITIES = {146 "toronto": ("Toronto", ""),147 "north-york": ("Toronto", "North York"),148 "etobicoke": ("Toronto", "Etobicoke"),149 "scarborough": ("Toronto", "Scarborough"),150 "mississauga": ("Mississauga", ""),151 "brampton": ("Brampton", ""),152 "oakville": ("Oakville", ""),153 "milton": ("Milton", ""),154 "burlington": ("Burlington", ""),155 "aurora": ("Aurora", ""),156 "newmarket": ("Newmarket", ""),157 "whitby": ("Whitby", ""),158 "oshawa": ("Oshawa", ""),159 "ottawa": ("Ottawa", ""),160 "hamilton": ("Hamilton", ""),161 "kitchener": ("Kitchener", ""),162 "waterloo": ("Waterloo", ""),163 "cambridge": ("Cambridge", ""),164 "london": ("London", ""),165 "cobourg": ("Cobourg", ""),166}167168_BED_TYPES = {"0": "Studio", "1": "3½", "2": "4½", "3": "5½", "4": "6½"}169_SKIP_IMG = re.compile(r"logo|icon|favicon|placeholder", re.I)170_PRICE_RE = re.compile(r"\$[\d,]+(?:\.\d{2})?")171172173class _BudgetReached(Exception):174 """Plafond de rendus atteint pour cette synchronisation."""175176177class RealstarConnector(BaseConnector):178 source_id = "realstar"179 request_delay = 1.0180 max_properties = 12 # garde-fou (2 rendus par propriété)181 max_images = 25182 max_renders = 20 # plafond de rendus par sync (hors cache)183 # Expansion Ontario 2026-08 (gaté LOUKA_ONTARIO) : plafonds séparés pour184 # ne jamais entamer le budget QC185 max_properties_on = 12186 max_renders_on = 24187188 # -- rendu JS avec attente (SPA + Cloudflare) — Scrapfly -------------------189 # (migré de Firecrawl le 2026-08-27 ; le retry court sur 5xx/vide, hérité190 # du fix realstar du 2026-08-27, vit désormais dans191 # BaseConnector.get_rendered, que les fixtures monkeypatchent)192 def _rendered(self, url: str, wait_ms: int = 9000) -> str:193 return self.get_rendered(url, wait_ms)194195 def fetch(self) -> list[Listing]:196 self._renders = 0197 html = self._rendered(SEARCH_URL, 10000)198 soup = BeautifulSoup(html, "html.parser")199 # [class*=…] : le rendu Scrapfly capture le DOM avant que le JS200 # RentCafe ne révèle les cartes (property-box-hidden) — les cartes201 # cachées sont complètes, le filtre QC en aval fait le tri202 cards = soup.select('li[class*="property-box"]')203 if not cards: # rendu incomplet : une seconde chance204 html = self._rendered(SEARCH_URL, 15000)205 soup = BeautifulSoup(html, "html.parser")206 cards = soup.select('li[class*="property-box"]')207208 listings: list[Listing] = []209 seen: set[str] = set()210 count = 0211 for card in cards:212 try:213 a = card.select_one("a[href*='/apartments/qc/']")214 if not a:215 continue # autre province216 url = (a.get("href") or "").split("?")[0]217 url = url.replace("http://", "https://")218 m = re.search(r"/apartments/qc/([a-z0-9\-.]+)/([a-z0-9\-]+)",219 url)220 if not m or url in seen:221 continue222 seen.add(url)223 city_slug, slug = m.group(1), m.group(2)224 if city_slug not in _GM_CITIES:225 continue # ville QC non répertoriée dans _GM_CITIES226 if count >= self.max_properties:227 break228 count += 1229 listings.append(230 self._property_listing(card, url, city_slug, slug))231 except Exception:232 continue233234 # Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO (rendu et budgets235 # séparés : l'échec ON ne doit jamais faire tomber la synchro QC)236 if _ONTARIO:237 try:238 listings.extend(self._fetch_ontario(seen))239 except Exception:240 pass241 return listings242243 def _fetch_ontario(self, seen: set[str]) -> list[Listing]:244 """Cartes /apartments/on/ de la recherche Ontario (mêmes gabarits245 RentCafe que le QC), plafonds propriétés/rendus dédiés."""246 # budget de rendus dédié à l'Ontario (le QC a déjà consommé le sien)247 self.max_renders = self._renders + self.max_renders_on248 html = self._rendered(ON_SEARCH_URL, 12000)249 soup = BeautifulSoup(html, "html.parser")250 cards = soup.select('li[class*="property-box"]')251 if not cards: # rendu incomplet : une seconde chance252 html = self._rendered(ON_SEARCH_URL, 15000)253 soup = BeautifulSoup(html, "html.parser")254 cards = soup.select('li[class*="property-box"]')255256 listings: list[Listing] = []257 count = 0258 for card in cards:259 try:260 a = card.select_one("a[href*='/apartments/on/']")261 if not a:262 continue # autre province263 url = (a.get("href") or "").split("?")[0]264 url = url.replace("http://", "https://")265 m = re.search(r"/apartments/on/([a-z0-9\-.]+)/([a-z0-9\-]+)",266 url)267 if not m or url in seen:268 continue269 seen.add(url)270 city_slug, slug = m.group(1), m.group(2)271 if city_slug not in _ON_CITIES:272 continue # ville ON hors des 7 régions couvertes273 if count >= self.max_properties_on:274 break275 count += 1276 listings.append(277 self._property_listing(card, url, city_slug, slug,278 province="ON"))279 except Exception:280 continue281 return listings282283 def _property_listing(self, card, url: str, city_slug: str,284 slug: str, province: str = "QC") -> Listing:285 city, sector = (_ON_CITIES if province == "ON"286 else _GM_CITIES)[city_slug]287 name = ""288 fav = card.select_one("[data-property]")289 if fav:290 name = (fav.get("data-property") or "").strip()291 if not name:292 h = card.select_one(".property-name a")293 if h:294 name = h.get_text(" ", strip=True)295 name = re.sub(r"\s*opens in a new tab\s*", "", name).strip()296 name = name or slug.replace("-", " ").title()297298 addr_el = card.select_one(".card-prop-address")299 address = addr_el.get_text(" ", strip=True) if addr_el else ""300 # Ontario : adresse suffixée « ON » (standard expansion 2026-08)301 if province == "ON" and address \302 and not re.search(r",?\s+ON\b", address):303 address = f"{address}, ON"304305 meta = card.select_one(".card-bed-bath-rent")306 beds = baths = sqft = ""307 if meta:308 items = [li.get_text(" ", strip=True)309 for li in meta.select("li")]310 for it in items:311 if "Bed" in it:312 beds = it313 elif "Bath" in it:314 baths = it315 elif "Sq" in it:316 sqft = it317 unit_type = ""318 bm = re.match(r"^(\d)(?:\s|-)?.*Bed", beds or "")319 if bm and "-" not in beds.split("Bed")[0]:320 unit_type = _BED_TYPES.get(bm.group(1), "")321322 # Fourchette de prix « $1,645.00 - $2,630.00 »323 card_text = card.get_text(" ", strip=True)324 price = None325 price_label = ""326 pm = re.search(r"\$[\d,]+(?:\.\d{2})?(?:(?:\s*(?:-|to))+\s*"327 r"\$[\d,]+(?:\.\d{2})?)?", card_text)328 if pm:329 price_label = re.sub(r"\s*to\s*-\s*", " - ", pm.group(0))330 first = price_label.split("-")[0].replace("$", "").replace(331 ",", "").replace("to", "").strip()332 try:333 price = float(first)334 except ValueError:335 price = parse_price(price_label)336 if "-" in price_label:337 price_label = "À partir de " + price_label338339 # Téléphone du bureau de location (lien tel: structuré de la carte)340 phone = ""341 tel = card.select_one("a[href^='tel:']")342 if tel:343 tm = re.search(r"\(?([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-]?(\d{4})",344 tel.get("href", ""))345 if tm:346 phone = f"{tm.group(1)}-{tm.group(2)}-{tm.group(3)}"347348 # Vignette de la carte349 images: list[str] = []350 img = card.select_one("img[src*='rentcafe']")351 if img and img.get("src"):352 images.append(img["src"])353354 # Pages détail (fiche + plans) via cache BD : rendu seulement si la355 # carte liste a changé (prix/dispo inclus dans le hash).356 key = hashlib.sha1(357 f"{name}|{address}|{beds}|{baths}|{sqft}|{price_label}"358 .encode("utf-8")).hexdigest()359 # uid : slug inchangé au QC ; préfixe « on- » en Ontario (aucun risque360 # de collision inter-provinces, cache détail séparé)361 ext = slug if province != "ON" else f"on-{slug}"362 try:363 payload = self.detail(ext, key, lambda: self._fetch_detail(url))364 except _BudgetReached:365 payload = {}366 except Exception:367 payload = {}368369 desc = payload.get("description", "")370 amenities = list(payload.get("amenities") or [])371 for im in (payload.get("images") or []):372 if im not in images:373 images.append(im)374375 # Plans structurés -> disponibilité, prix « à partir de », superficie376 availability = ""377 area_sqft = None378 plans = payload.get("floorplans") or []379 avail_plans = [p for p in plans if p.get("available", 0) > 0]380 if plans:381 total = sum(p.get("available", 0) for p in avail_plans)382 if total > 0:383 availability = (f"{total} unité(s) disponible(s) — "384 + ", ".join(p["name"] for p in avail_plans[:6]))385 prices = [p["price"] for p in avail_plans386 if p.get("price") and 100 <= p["price"] <= 20000]387 if prices:388 price = min(prices)389 price_label = (f"À partir de {price:,.0f} $/mois"390 .replace(",", " ")391 if len(avail_plans) > 1 or len(prices) > 1392 else f"{price:,.0f} $/mois".replace(",", " "))393 if len(avail_plans) == 1 and avail_plans[0].get("sqft"):394 # une seule unité type disponible : sa superficie est fiable395 area_sqft = avail_plans[0]["sqft"]396 if avail_plans[0].get("unit_type"):397 unit_type = avail_plans[0]["unit_type"]398399 # Résumé des plans disponibles dans la description (texte fidèle)400 plan_bits = []401 for p in avail_plans[:8]:402 seg = p["name"]403 if p.get("sqft"):404 seg += f" ({p['sqft']:.0f} pi²)"405 if p.get("price"):406 seg += f" : {p['price']:,.0f} $/mois".replace(",", " ")407 plan_bits.append(seg)408409 details: dict = {}410 if phone:411 details["contact"] = {"phone": phone}412413 bits = [b for b in [beds, baths, sqft] if b]414 desc_parts = ([desc] if desc else []) + bits415 if plan_bits:416 desc_parts.append("Disponibles : " + " ; ".join(plan_bits))417 return Listing(418 source=self.source_id,419 external_id=ext,420 url=url,421 title=name,422 address=address,423 sector=sector,424 city=city,425 province=province,426 unit_type=unit_type,427 price=price,428 price_label=price_label,429 availability=availability,430 area_sqft=area_sqft,431 description=" — ".join(desc_parts)[:900],432 amenities=amenities,433 details=details,434 images=images[: self.max_images],435 )436437 # -- pages détail (fiche propriété + plans) --------------------------------438 def _fetch_detail(self, url: str) -> dict:439 """2 rendus Scrapfly : fiche (photos, description, points forts) et440 /floorplans (plans structurés). Appelé seulement hors cache."""441 if self._renders + 2 > self.max_renders:442 raise _BudgetReached()443 self._renders += 2444445 payload: dict = {"description": "", "amenities": [], "images": [],446 "floorplans": []}447 try:448 ph = self._rendered(url, 8000)449 psoup = BeautifulSoup(ph, "html.parser")450 for im in psoup.select("img[src*='resource.rentcafe.com']"):451 src = im.get("src", "")452 if src and not _SKIP_IMG.search(src) \453 and src not in payload["images"]:454 payload["images"].append(src)455 # description : premiers paragraphes substantiels456 paras = [p.get_text(" ", strip=True)457 for p in psoup.find_all("p")]458 paras = [p for p in paras if len(p) > 80]459 if paras:460 payload["description"] = " ".join(paras[:2])[:600]461 # points forts de la propriété (courtes mentions après le titre)462 text = psoup.get_text("\n", strip=True)463 hm = re.search(r"Points forts de la propri[ée]t[ée]\n(.*?)\n"464 r"(?:Photos|Emplacement|Votre)", text, re.S)465 if not hm: # gabarit anglais (fiches Ontario)466 hm = re.search(r"Property Highlights\n(.*?)\n"467 r"(?:Photos|Location|Your)", text, re.S)468 if hm:469 amenities = []470 for t in hm.group(1).split("\n"):471 t = t.strip()472 if 2 < len(t) < 50 and t not in amenities:473 amenities.append(t)474 payload["amenities"] = amenities[:15]475 except Exception:476 pass477478 try:479 fh = self._rendered(url.rstrip("/") + "/floorplans", 10000)480 payload["floorplans"] = self._parse_floorplans(fh)481 except Exception:482 pass483 return payload484485 @staticmethod486 def _parse_floorplans(html: str) -> list[dict]:487 """Cartes de plans RentCafe : nom (« 4 ½ D »), chambres, pi², prix,488 nombre d'unités disponibles (structuré : .fp-availability)."""489 soup = BeautifulSoup(html, "html.parser")490 plans: list[dict] = []491 for cont in soup.select("div[id^='fp-container-']"):492 try:493 name_el = cont.select_one("span[data-selenium-id$='Name']")494 name = name_el.get_text(" ", strip=True) if name_el else ""495 if not name:496 continue497 avail = 0498 av_el = cont.select_one(".fp-availability")499 if av_el:500 am = re.search(r"(\d+)", av_el.get_text(" ", strip=True))501 if am:502 avail = int(am.group(1))503 sqft = None504 sq_el = cont.select_one("span[data-selenium-id$='SqFt']")505 if sq_el:506 # « Pi. Ca. » (gabarit FR) ou « Sq. Ft. » (gabarit EN/ON)507 sm = re.search(r"([\d,]{2,})\s*(?:Pi|Sq)",508 sq_el.get_text(" ", strip=True), re.I)509 if sm:510 v = float(sm.group(1).replace(",", ""))511 if 80 <= v <= 20000:512 sqft = v513 price = None514 pm = _PRICE_RE.search(cont.get_text(" ", strip=True))515 if pm:516 v = float(pm.group(0).replace("$", "").replace(",", ""))517 if 100 <= v <= 20000:518 price = v519 unit_type = ""520 um = re.match(r"^\s*(\d)\s*½", name)521 if um:522 n = int(um.group(1))523 unit_type = "6½+" if n >= 6 else f"{n}½"524 elif re.match(r"(?i)^\s*(?:studio|bachelor)", name):525 unit_type = "Studio"526 else:527 # gabarits anglais (plans Ontario) : « 2 Bed 1 Bath A »,528 # « One Bedroom », etc. -> convention QC (n + 2)½529 wm = re.match(r"(?i)^\s*(\d|one|two|three|four)\s*bed",530 name)531 if wm:532 n = {"one": 1, "two": 2, "three": 3, "four": 4}.get(533 wm.group(1).lower()) or int(wm.group(1))534 # aligné sur _BED_TYPES : 4 chambres -> 6½535 unit_type = "6½+" if n >= 5 else f"{n + 2}½"536 plans.append({"name": name, "available": avail,537 "sqft": sqft, "price": price,538 "unit_type": unit_type})539 except Exception:540 continue541 return plans542