Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/boardwalk.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/boardwalk.py : connecteur Boardwalk REIT (bwalk.com)91# Pages de villes de la région de Montréal rendues serveur (HubSpot CMS) :92# Longueuil, Laval, Île-des-Sœurs/Verdun, Ville Saint-Laurent. Fiches93# propriétés avec cartes de types de suites (« À partir de … $ ») qui94# portent aussi superficie (pi ca), c. à c./sdb et le statut (« N logements95# disponibles » / « liste d'attente ») ; adresse complète + téléphone dans96# l'en-tête (p.address-and-phone). Les pages de suites ne servent plus qu'aux97# photos spécifiques, via le cache self.detail().98# REIT pancanadien : seules les propriétés du Grand Montréal sont couvertes.99# Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO=1 : mêmes pages de villes100# rendues serveur en fr-ca pour London et Kitchener/Waterloo (libellés101# français identiques : « À partir de … $ », « Superficie (pi ca) »,102# « c. à c. », « sdb »). L'URL des propriétés ON porte le quartier :103# /fr-ca/appartements-a-louer-a-<ville>/<quartier>/<propriété>. Sans la104# variable d'environnement, comportement strictement identique (prod QC).105# -----------------------------------------------------------------------------106from __future__ import annotations107108import hashlib109import os110import re111112from bs4 import BeautifulSoup113114from ..schema import Listing, normalize_unit_type, parse_price115from .base import BaseConnector116117BASE = "https://www.bwalk.com"118119# Pages de villes du Grand Montréal -> (ville réelle, secteur par défaut)120CITY_PAGES = {121 f"{BASE}/fr-ca/appartements-a-louer-a-montreal-longueuil":122 ("Longueuil", ""),123 f"{BASE}/fr-ca/appartements-a-louer-a-montreal-laval":124 ("Laval", ""),125 f"{BASE}/fr-ca/appartements-a-louer-a-montreal-nuns-island-verdun":126 ("Montréal", "Île-des-Sœurs (Verdun)"),127 f"{BASE}/fr-ca/appartements-a-louer-a-montreal-ville-saint-laurent":128 ("Montréal", "Saint-Laurent"),129}130131PROP_RE = re.compile(132 r'href="(/fr-ca/appartements-a-louer-a-montreal-[a-z0-9\-]+/'133 r'[a-z0-9\-]+/[a-z0-9\-]+)"')134135# --- Expansion Ontario (gaté LOUKA_ONTARIO=1 ; prod QC intacte sans) ---------136_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"137138# Pages de villes de l'Ontario (fr-ca) -> ville réelle ; le quartier vient du139# 2e segment de l'URL de la propriété (ex. /…-a-london/carling/<propriété>)140CITY_PAGES_ON = {141 f"{BASE}/fr-ca/appartements-a-louer-a-london": "London",142 f"{BASE}/fr-ca/appartements-a-louer-a-kitchener": "Kitchener",143}144145_POSTAL_RE = re.compile(r",\s*([A-Z]\d[A-Z]\s?\d[A-Z]\d)\s*$")146147148def _addr_on(address: str) -> str:149 """Suffixe « ON » à l'adresse (avant le code postal s'il termine)."""150 if not address or re.search(r"\bON\b", address):151 return address152 m = _POSTAL_RE.search(address)153 if m:154 return f"{address[: m.start()].rstrip(', ')}, ON, {m.group(1)}"155 return f"{address}, ON"156PRICE_RE = re.compile(r'À partir de\s*([\d\s\u00a0,.]+\$)')157# superficie : « 900 », « 648 - 760 », « 1 408 » (séparateur de milliers) —158# le nombre de chambres qui suit (« 3 c. à c. ») ne doit pas être aspiré159AREA_RE = re.compile(160 r'Superficie\s*\(pi\s*ca\)\s*:?\s*([\d\s\u00a0-]+?)'161 r'\s*(?:\d+\s*c\.\s*à\s*c\.|\||sdb|[A-Za-z]|$)')162BEDS_RE = re.compile(r'(\d+)\s*c\.\s*à\s*c\.')163BATHS_RE = re.compile(r'(\d+)\s*sdb')164PHONE_RE = re.compile(r'\(?(\d{3})\)?[\s.\-]?(\d{3})[\s.\-](\d{4})')165166167_BED_TYPES = {1: "3½", 2: "4½", 3: "5½", 4: "6½"}168169170def _suite_type(name: str) -> str:171 """« 3 1/2 Pièces » -> 3½ ; « Maison en Rangée avec N Chambres » -> Maison ;172 « 2 Chambres » -> 4½."""173 low = name.lower()174 if "maison" in low or "rang" in low:175 return "Maison"176 m = re.search(r"(\d)\s*chambre", low)177 if m:178 return _BED_TYPES.get(int(m.group(1)), "")179 return normalize_unit_type(name)180181182class BoardwalkConnector(BaseConnector):183 source_id = "boardwalk"184 request_delay = 0.6185 max_properties = 25 # garde-fou (QC)186 max_properties_on = 25 # garde-fou distinct pour l'Ontario (gaté)187 max_images = 25188189 def fetch(self) -> list[Listing]:190 listings: list[Listing] = []191 seen: set[str] = set()192 count = 0193 for city_url, (city, default_sector) in CITY_PAGES.items():194 try:195 html = self.get(city_url).text196 except Exception:197 continue198 for path in dict.fromkeys(PROP_RE.findall(html)):199 if path in seen:200 continue201 seen.add(path)202 if count >= self.max_properties:203 break204 count += 1205 try:206 listings.extend(207 self._property_listings(path, city, default_sector))208 except Exception:209 continue210211 # Expansion Ontario (gaté LOUKA_ONTARIO=1) : mêmes pages fr-ca, budget212 # de propriétés distinct pour ne rien enlever à la couverture QC213 if _ONTARIO:214 count_on = 0215 for city_url, city in CITY_PAGES_ON.items():216 try:217 html = self.get(city_url).text218 except Exception:219 continue220 prop_re = re.compile(221 r'href="(' + re.escape(city_url[len(BASE):]) +222 r'/[a-z0-9\-]+/[a-z0-9\-]+)"')223 for path in dict.fromkeys(prop_re.findall(html)):224 if path in seen:225 continue226 seen.add(path)227 if count_on >= self.max_properties_on:228 break229 count_on += 1230 # quartier dérivé de l'URL (ex. white-oaks -> White Oaks)231 sector = (path.rstrip("/").split("/")[-2]232 .replace("-", " ").title())233 try:234 listings.extend(self._property_listings(235 path, city, sector, province="ON"))236 except Exception:237 continue238239 # Unicité des external_id (deux cartes peuvent pointer vers la même240 # page de type de suite avec des prix différents)241 used: dict[str, int] = {}242 for lst in listings:243 n = used.get(lst.external_id, 0)244 used[lst.external_id] = n + 1245 if n:246 lst.external_id = f"{lst.external_id}-{n + 1}"247 return listings248249 def _property_listings(self, path: str, city: str,250 default_sector: str,251 province: str = "QC") -> list[Listing]:252 url = BASE + path253 prop_slug = path.rstrip("/").split("/")[-1]254 html = self.get(url).text255 soup = BeautifulSoup(html, "html.parser")256257 t = soup.find("title")258 name = (t.get_text(strip=True).split("|")[0].strip()259 if t else prop_slug.replace("-", " "))260261 # Adresse complète + téléphone : en-tête <p class="address-and-phone">262 address = ""263 phone = ""264 ap = soup.select_one("p.address-and-phone")265 if ap:266 ap_text = re.sub(r"\s+", " ", ap.get_text(" ", strip=True))267 pm_ = PHONE_RE.search(ap_text)268 if pm_:269 phone = "-".join(pm_.groups())270 ap_text = ap_text[: pm_.start()].strip(" ,")271 address = ap_text272 if not address:273 # repli : texte alt des photos « photo de la propriété pour le … »274 am = re.search(275 r'photo de la propri[ée]t[ée] pour le\s*([^"<>]{5,90})', html)276 if am:277 address = am.group(1).strip()278 if province == "ON":279 address = _addr_on(address)280281 # Galerie photo (swiper)282 images: list[str] = []283 for img in soup.select("img[src]"):284 src = img.get("src", "")285 if re.search(r"hubfs/.*(bw_properties|Web%20Photos|Web Photos)",286 src) and src.startswith("http"):287 if src not in images:288 images.append(src)289 images = images[: self.max_images]290291 # Description de la propriété292 desc = ""293 dh = soup.find(string=re.compile("Description de la propriété"))294 if dh:295 sec = dh.find_parent()296 nxt = sec.find_next("p") if sec else None297 if nxt:298 desc = nxt.get_text(" ", strip=True)[:600]299 if not desc:300 og = soup.find("meta", attrs={"property": "og:description"})301 if og and og.get("content"):302 desc = og["content"].strip()[:600]303304 # Commodités (« Caractéristiques et espaces d'agrément »)305 amenities: list[str] = []306 ah = soup.find(string=re.compile("Caractéristiques et espaces"))307 if ah:308 cont = ah.find_parent()309 for _ in range(3):310 if cont is None:311 break312 lis = cont.find_all("li")313 if lis:314 break315 cont = cont.parent316 if cont:317 for li in cont.find_all("li")[:25]:318 txt = li.get_text(" ", strip=True)319 if txt and len(txt) < 50 and txt not in amenities:320 amenities.append(txt)321322 # Cartes de types de suites : <h4 class="highlight-suite"><a href=...>323 # La carte porte prix, superficie (pi ca), c. à c. et sdb ; le groupe324 # parent (div.unit_type) porte le statut (« N logements disponibles »325 # ou « liste d'attente »). Plus besoin de visiter la fiche de suite326 # pour ces champs — elle ne sert qu'aux photos (via self.detail).327 listings: list[Listing] = []328 for h4 in soup.select("h4.highlight-suite"):329 try:330 a = h4.find("a")331 if not a:332 continue333 suite_name = a.get_text(" ", strip=True)334 suite_href = a.get("href") or ""335 suite_url = (BASE + suite_href336 if suite_href.startswith("/") else suite_href)337 card = h4.parent338 card_text = re.sub(r"\s+", " ", card.get_text(" ", strip=True)339 if card else "")340 price_label = ""341 pm = PRICE_RE.search(card_text)342 if pm:343 price_label = "À partir de " + pm.group(1).strip()344 price = parse_price(price_label)345346 # Superficie / chambres / sdb depuis la carte elle-même347 detail_bits: list[str] = []348 suite_amenities = amenities349 am_ = AREA_RE.search(card_text)350 if am_:351 rng = re.sub(r"[\s ]+", " ", am_.group(1)).strip()352 detail_bits.append(f"Superficie (pi ca) : {rng}")353 lo = re.sub(r"[\s\u00a0]", "", rng.split("-")[0])354 if lo.isdigit():355 # borne basse -> texte brut, finalize() dérive area_sqft356 suite_amenities = amenities + [f"{lo} pi ca"]357 bm = BEDS_RE.search(card_text)358 if bm:359 detail_bits.append(f"{bm.group(1)} c. à c.")360 sm = BATHS_RE.search(card_text)361 if sm:362 detail_bits.append(f"{sm.group(1)} sdb")363364 # Statut du groupe : disponible ou liste d'attente365 availability = "Disponible"366 if re.search(r"liste d.attente", card_text, re.I):367 availability = "Sur la liste d'attente"368 else:369 group = card.find_parent(class_="unit_type") if card else None370 if group:371 gm = re.search(r"(\d+)\s*logements?\s*disponibles?",372 group.get_text(" ", strip=True), re.I)373 if gm:374 availability = f"{gm.group(1)} logement(s) disponible(s)"375376 # Photos spécifiques de la suite (page détail, cache BD)377 suite_imgs: list[str] = []378 if suite_url.startswith(BASE) and self.use_detail_cache:379 key = hashlib.sha1(380 (suite_url + "|" + card_text).encode("utf-8")).hexdigest()381 payload = self.detail(382 f"{prop_slug}-{suite_href.rstrip('/').split('/')[-1]}",383 key, lambda u=suite_url: self._suite_images(u))384 suite_imgs = payload.get("images") or []385386 type_slug = (suite_href.rstrip("/").split("/")[-1]387 or re.sub(r"[^a-z0-9]+", "-",388 suite_name.lower()).strip("-"))389 details = {"contact": {"phone": phone}} if phone else {}390 listings.append(Listing(391 source=self.source_id,392 external_id=f"{prop_slug}-{type_slug}",393 url=suite_url or url,394 title=f"{name} — {suite_name}",395 address=address,396 sector=default_sector,397 city=city,398 province=province,399 unit_type=_suite_type(suite_name),400 price=price,401 price_label=price_label,402 availability=availability,403 description=" — ".join(404 x for x in [desc] + detail_bits if x)[:600],405 amenities=suite_amenities,406 details=details,407 images=(suite_imgs or images)[: self.max_images],408 ))409 except Exception:410 continue411 return listings412413 def _suite_images(self, suite_url: str) -> dict:414 """Photos propres à un type de suite (page détail de la suite)."""415 try:416 sh = self.get(suite_url).text417 except Exception:418 return {}419 imgs: list[str] = []420 ssoup = BeautifulSoup(sh, "html.parser")421 for img in ssoup.select("img[src]"):422 src = img.get("src", "")423 if (re.search(r"hubfs/.*(bw_properties|Web%20Photos|Web Photos)",424 src) and src.startswith("http")425 and src not in imgs):426 imgs.append(src)427 return {"images": imgs[: self.max_images]}428