Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/mountbridge.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-10-1114#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/mountbridge.py : connecteur MountBridge (mountbridge.ca)91# Gestionnaire montréalais (~90 immeubles : Montréal, Longueuil,92# Sainte-Thérèse…), inventaire complet incluant le projet ELEVA.93# Refonte du site 2026-10-07 : le WordPress/Elementor (/properties/,94# /property/<slug>/) a été remplacé par une app Lovable (React + TanStack95# Router SSR, backend Supabase). Les ~90 fiches /buildings/<slug> sont96# listées dans le HTML statique de /buildings ; chaque fiche rend côté97# serveur ses types d'unités en cartes .aa-card (.aa-rooms « 3½ »,98# .aa-type « 1 bed », .aa-pill « Available »/« Unavailable », .aa-price99# « $1,395 »), un JSON-LD ApartmentComplex (quartier containedInPlace) et100# un payload d'hydratation TSR (address_line, lat/lon, property_id).101# Une annonce par type DISPONIBLE, id stable <slug>-<rooms sans ½>.102# ⚠️ Images = URLs Supabase storage SIGNÉES (token ~24 h, re-signé à103# chaque rendu SSR) : pas de cache détail — chaque sync (~3,4 h)104# rafraîchit les jetons, sinon les photos expireraient en BD.105# -----------------------------------------------------------------------------106from __future__ import annotations107108import json109import re110111from bs4 import BeautifulSoup112113from ..schema import Listing114from .base import BaseConnector115116BASE = "https://mountbridge.ca"117LIST_URL = f"{BASE}/buildings"118119_SLUG_RE = re.compile(r'href="/buildings/([a-z0-9-]+)"')120_IMG_RE = re.compile(121 r'https://[a-z0-9-]+\.lovable\.cloud/storage/v1/object/sign/'122 r'property-media/(mb_\d+)/[^"\s\\]+\?token=[A-Za-z0-9._-]+')123_PRICE_RE = re.compile(r"\$\s*([\d][\d,\s]*\d|\d)")124_BEDS_RE = re.compile(r"(\d+)\s*bed", re.I)125126127class MountbridgeConnector(BaseConnector):128 source_id = "mountbridge"129 request_delay = 0.6130 max_properties = 150 # garde-fou (90 fiches à l'écriture)131 max_images = 20132133 def fetch(self) -> list[Listing]:134 page = self.get(LIST_URL).text135 slugs = list(dict.fromkeys(_SLUG_RE.findall(page)))136 if not slugs:137 # gabarit remanié ou page parquée ≠ vrai zéro (pattern sotramont)138 raise RuntimeError(139 "mountbridge: aucun lien /buildings/<slug> sur la page de "140 "liste — gabarit changé ou page vide, sync interrompu")141142 listings: list[Listing] = []143 failures = 0144 for i, slug in enumerate(slugs):145 if i >= self.max_properties:146 break147 try:148 listings.extend(self._building_listings(slug))149 except Exception:150 failures += 1151 continue152 if failures == len(slugs):153 raise RuntimeError(154 "mountbridge: toutes les fiches immeuble ont échoué au "155 f"parsing ({failures}/{len(slugs)}) — gabarit changé ?")156 return listings157158 def _building_listings(self, slug: str) -> list[Listing]:159 url = f"{BASE}/buildings/{slug}"160 page = self.get(url).text161 soup = BeautifulSoup(page, "html.parser")162163 name = soup.h1.get_text(" ", strip=True) if soup.h1 else slug164 sector = ""165 for s in soup.select('script[type="application/ld+json"]'):166 try:167 ld = json.loads(s.string or "")168 except ValueError:169 continue170 if ld.get("@type") == "ApartmentComplex":171 sector = (ld.get("containedInPlace") or {}).get("name") or ""172 break173174 # payload d'hydratation TSR : objet building en littéral JS175 esc = re.escape(slug)176 address = ""177 m = re.search(r'slug:"%s"[^{}]*?address_line:"([^"]*)"' % esc, page)178 if m:179 address = re.sub(r",?\s*Canada\s*$", "",180 re.sub(r"\s+", " ", m.group(1))).strip()181 # ville : segment de address_line devant « QC » — le champ city du182 # payload est parfois pollué (« Fort Street », « Avenue Summerhill »)183 city = ""184 parts = [p.strip() for p in address.split(",")]185 for i, p in enumerate(parts):186 if re.match(r"^(QC|Québec|Quebec)\b", p) and i >= 2:187 city = parts[i - 1]188 break189 if not city:190 m = re.search(r'slug:"%s"[^{}]*?city:"([^"]*)"' % esc, page)191 city = (m.group(1) if m and m.group(1) else "Montréal")192 lat = lng = None193 m = re.search(r'slug:"%s"[^{}]*?lat:(-?\d+(?:\.\d+)?),'194 r'lon:(-?\d+(?:\.\d+)?)' % esc, page)195 if m:196 lat, lng = float(m.group(1)), float(m.group(2))197198 desc = " ".join(p.get_text(" ", strip=True)199 for p in soup.select("p.bd-about-p"))[:600]200201 amenities: list[str] = []202 feats = soup.find(id="features")203 if feats:204 for li in feats.select("li"):205 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True)).strip()206 t = re.sub(r"^P\s+(?=Parking)", "", t)207 if t and len(t) < 60 and t not in amenities:208 amenities.append(t)209 amenities = amenities[:25]210211 # photos : URLs signées scoping sur le property_id de CETTE fiche212 # (la page embarque aussi les photos des immeubles « comparables »)213 prop_id = ""214 m = re.search(r'property_id:"(mb_\d+)"', page)215 if m:216 prop_id = m.group(1)217 images: list[str] = []218 seen_paths: set[str] = set()219 for im in _IMG_RE.finditer(page):220 if prop_id and im.group(1) != prop_id:221 continue222 u = im.group(0)223 path = u.split("?", 1)[0]224 if path in seen_paths:225 continue226 seen_paths.add(path)227 images.append(u)228 images = images[: self.max_images]229230 out: list[Listing] = []231 seen: dict[str, int] = {}232 for card in soup.select(".aa-card"):233 pill = card.select_one(".aa-pill")234 status = pill.get_text(" ", strip=True).lower() if pill else ""235 if "available" not in status or "unavailable" in status:236 continue237 rooms_el = card.select_one(".aa-rooms")238 type_el = card.select_one(".aa-type")239 price_el = card.select_one(".aa-price")240 rooms = rooms_el.get_text(" ", strip=True) if rooms_el else ""241 typ = type_el.get_text(" ", strip=True) if type_el else ""242 price_txt = price_el.get_text(" ", strip=True) if price_el else ""243244 price = None245 pm = _PRICE_RE.search(price_txt)246 if pm:247 try:248 price = float(re.sub(r"[^\d]", "", pm.group(1)))249 except ValueError:250 price = None251 if price is not None and not (100 <= price <= 20000):252 price = None253254 bm = _BEDS_RE.search(typ)255 if bm:256 bedrooms: float | None = float(bm.group(1))257 label = f"{bm.group(1)} chambre(s)"258 elif "studio" in typ.lower():259 bedrooms = 0.0260 label = ("Studio + pièce fermée" if "room" in typ.lower()261 else "Studio")262 else:263 bedrooms = None264 label = typ265266 typo = rooms.replace("½", "5").replace(" ", "") or "x"267 ext = f"{slug}-{typo}"268 seen[ext] = seen.get(ext, 0) + 1269 if seen[ext] > 1: # doublon de type sur la même fiche270 ext = f"{ext}-{seen[ext]}"271272 out.append(Listing(273 source=self.source_id,274 external_id=ext,275 url=url,276 title=f"{name} — {label}" if label else name,277 address=address,278 sector=sector,279 city=city,280 unit_type=rooms,281 bedrooms=bedrooms,282 bathrooms=None,283 price=price,284 price_label=(f"À partir de {int(price)} $/mois"285 if price else price_txt),286 availability="",287 area_sqft=None,288 description=desc,289 amenities=list(amenities),290 images=list(images),291 lat=lat,292 lng=lng,293 ))294 return out295