Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/brigil.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# 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/brigil.py : connecteur Brigil (brigil.com — Gatineau/Outaouais)91# Promoteur-gestionnaire dominant de Gatineau. Site = portail Yardi RentCafe92# protégé par Cloudflare : curl/requests reçoivent 403 (« Just a moment »),93# TOUT passe par le rendu Scrapfly avec attente (ex-Firecrawl) — même patron que94# realstar.py (RentCafe + Cloudflare) :95# 1) /searchlisting?province=Quebec -> cartes propriétés (nom, gamme96# Aura/Apogee/Comfort, lits, fourchette de prix, vignette) ; le portail97# ne filtre PAS par ville côté serveur et les cartes ne portent pas la98# ville : elle est lue sur la fiche de chaque propriété ;99# 2) fiche propriété -> adresse structurée (itemprop=address), photos,100# description, plus les plans quand ils y sont intégrés ;101# 3) /floorplans si la fiche n'a pas de plans -> plans structurés102# (nom, chambres, sdb, pi², « Starting at »).103# Les propriétés d'Ottawa/Ontario sont écartées : d'abord par l'URL104# (/apartments/on/…), ensuite par la ville lue sur la fiche.105# Une annonce par propriété. Les rendus passent par self.detail(...) (cache106# BD) : le rendu n'est rappelé que si la carte a changé, et un plafond107# (max_renders) borne le coût de chaque synchronisation.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import hashlib112import re113114from bs4 import BeautifulSoup115116from ..schema import Listing, normalize_unit_type, parse_price, strip_accents117from .base import BaseConnector118119SEARCH_URL = "https://www.brigil.com/searchlisting?province=Quebec"120121# Villes desservies côté québécois (Gatineau + couronne outaouaise). Les122# anciennes villes fusionnées deviennent des secteurs de Gatineau.123_GATINEAU_SECTORS = {124 "hull": "Hull", "aylmer": "Aylmer", "buckingham": "Buckingham",125 "masson-angers": "Masson-Angers", "templeton": "Templeton",126 "gatineau": "",127}128_QC_CITIES = {129 "gatineau": "Gatineau", "hull": "Gatineau", "aylmer": "Gatineau",130 "buckingham": "Gatineau", "chelsea": "Chelsea", "cantley": "Cantley",131 "val-des-monts": "Val-des-Monts", "thurso": "Thurso",132 "la peche": "La Pêche",133}134135_SKIP_IMG = re.compile(r"logo|icon|favicon|placeholder", re.I)136_PRICE_RE = re.compile(r"\$[\d,]+(?:\.\d{2})?")137_BED_LOW_RE = re.compile(r"(?i)^\s*(studio|\d+)")138139140class _BudgetReached(Exception):141 """Plafond de rendus atteint pour cette synchronisation."""142143144class BrigilConnector(BaseConnector):145 source_id = "brigil"146 request_delay = 1.0147 max_images = 20148 max_renders = 26 # plafond de rendus par sync (hors cache)149150 # -- rendu JS avec attente (RentCafe + Cloudflare) — Scrapfly --------------151 # (migré de Firecrawl le 2026-08-27 ; retry + échec honnête dans152 # BaseConnector.get_rendered, que les fixtures monkeypatchent)153 def _rendered(self, url: str, wait_ms: int = 9000) -> str:154 return self.get_rendered(url, wait_ms)155156 # -- helpers ---------------------------------------------------------------157 @staticmethod158 def _slug(url: str) -> str:159 """URL de propriété -> identifiant stable (1er segment du chemin)."""160 m = re.search(r"brigil\.com/(?:apartments/[a-z]{2}/[^/]+/)?([^/?#]+)",161 url)162 if not m:163 return ""164 slug = m.group(1)165 return "" if slug in ("searchlisting", "default.aspx") else slug166167 @staticmethod168 def _city_sector(address: str) -> tuple[str, str]:169 """Ville et secteur lus DANS l'adresse publiée par la fiche.170171 Retourne ('', '') si l'adresse ne nomme aucune ville québécoise172 desservie (propriété ontarienne ou adresse illisible).173 """174 key = strip_accents(address or "").lower()175 if re.search(r"\bon\b|ontario", key) and not re.search(r"\bqc\b|quebec",176 key):177 return "", ""178 city, sector = "", ""179 for token, canon in _QC_CITIES.items():180 if re.search(rf"\b{re.escape(token)}\b", key):181 city = canon182 break183 if city == "Gatineau":184 for token, canon in _GATINEAU_SECTORS.items():185 if canon and re.search(rf"\b{re.escape(token)}\b", key):186 sector = canon187 break188 return city, sector189190 @staticmethod191 def _unit_type(beds: str) -> str:192 """« Studio-2 Beds » -> Studio ; « 2-3 Beds » -> 4½ (borne basse, en193 cohérence avec le prix « à partir de » de la carte)."""194 m = _BED_LOW_RE.match(beds or "")195 if not m:196 return ""197 low = m.group(1).lower()198 if low == "studio":199 return "Studio"200 n = int(low)201 return "Studio" if n == 0 else normalize_unit_type(f"{n} chambres")202203 # -- fetch -----------------------------------------------------------------204 def fetch(self) -> list[Listing]:205 self._renders = 0206 html = self._rendered(SEARCH_URL, 10000)207 soup = BeautifulSoup(html, "html.parser")208 # [class*=…] : le rendu Scrapfly capture le DOM avant que le JS209 # RentCafe ne révèle les cartes (property-box-hidden) — les cartes210 # cachées sont complètes, le filtre QC en aval fait le tri211 cards = soup.select('li[class*="property-box"]')212 if not cards: # rendu incomplet : seconde chance213 html = self._rendered(SEARCH_URL, 15000)214 soup = BeautifulSoup(html, "html.parser")215 cards = soup.select('li[class*="property-box"]')216217 # candidats : tout sauf les fiches explicitement ontariennes218 candidates: list[tuple[str, str, object]] = []219 seen: set[str] = set()220 for card in cards:221 a = card.select_one("a[href*='brigil.com']")222 if not a:223 continue224 url = (a.get("href") or "").split("?")[0].replace("http://",225 "https://")226 if "/apartments/on/" in url:227 continue # Ottawa / Ontario228 slug = self._slug(url)229 if not slug or slug in seen:230 continue231 seen.add(slug)232 candidates.append((slug, url, card))233 # les URLs qui annoncent déjà /qc/ passent en premier (rendu utile sûr)234 candidates.sort(key=lambda c: 0 if "/apartments/qc/" in c[1] else 1)235236 listings: list[Listing] = []237 for slug, url, card in candidates:238 try:239 lst = self._property_listing(slug, url, card)240 except _BudgetReached:241 break # budget épuisé : au prochain sync242 except Exception:243 continue244 if lst is not None:245 listings.append(lst)246 return listings247248 def _property_listing(self, slug: str, url: str, card) -> Listing | None:249 name = ""250 fav = card.select_one("[data-property]")251 if fav:252 name = (fav.get("data-property") or "").strip()253 if not name:254 h = card.select_one(".property-name a")255 if h:256 name = h.get_text(" ", strip=True)257 name = re.sub(r"\s*opens in a new tab\s*", "", name).strip()258 name = name or slug.replace("-", " ").title()259260 types_el = card.select_one(".unit-types")261 unit_types = types_el.get_text(" ", strip=True) if types_el else ""262 beds = ""263 for li in card.select("ul.list-inline li"):264 txt = li.get_text(" ", strip=True)265 if re.search(r"(?i)bed|studio", txt):266 beds = txt267 break268269 card_text = card.get_text(" ", strip=True)270 price = None271 price_label = ""272 pm = re.search(r"\$[\d,]+(?:\.\d{2})?(?:(?:\s*(?:-|to))+\s*"273 r"\$[\d,]+(?:\.\d{2})?)?", card_text)274 if pm:275 price_label = re.sub(r"\s*to\s*-\s*", " - ", pm.group(0))276 price = parse_price(price_label.split("-")[0])277 if "-" in price_label:278 price_label = "À partir de " + price_label279280 images: list[str] = []281 img = card.select_one("img[src*='rentcafe']")282 if img and img.get("src"):283 images.append(img["src"])284285 # fiche propriété (+ plans) via cache BD : le rendu n'est rappelé que286 # si la carte a changé (nom, lits, prix)287 key = hashlib.sha1(288 f"{name}|{unit_types}|{beds}|{price_label}".encode("utf-8")289 ).hexdigest()[:20]290 payload = self.detail(slug, key, lambda: self._fetch_detail(url))291292 city = payload.get("city", "")293 if not city:294 return None # ville non québécoise ou fiche illisible295 sector = payload.get("sector", "")296 address = payload.get("address", "")297298 for im in (payload.get("images") or []):299 if im not in images:300 images.append(im)301302 area_sqft = None303 unit_type = self._unit_type(beds)304 plans = payload.get("floorplans") or []305 priced = [p for p in plans if p.get("price")]306 if priced:307 low = min(p["price"] for p in priced)308 if 100 <= low <= 20000:309 price = low310 price_label = (f"À partir de {low:,.0f} $/mois"311 .replace(",", " ") if len(priced) > 1312 else f"{low:,.0f} $/mois".replace(",", " "))313 if len(plans) == 1 and plans[0].get("sqft"):314 area_sqft = plans[0]["sqft"]315 if plans[0].get("unit_type"):316 unit_type = plans[0]["unit_type"]317318 plan_bits = []319 for p in plans[:8]:320 seg = p["name"]321 if p.get("sqft"):322 seg += f" ({p['sqft']:.0f} pi²)"323 if p.get("price"):324 seg += f" : {p['price']:,.0f} $/mois".replace(",", " ")325 plan_bits.append(seg)326327 desc_parts = [x for x in [payload.get("description", ""),328 unit_types, beds] if x]329 if plan_bits:330 desc_parts.append("Plans : " + " ; ".join(plan_bits))331332 details: dict = {}333 if payload.get("phone"):334 details["contact"] = {"phone": payload["phone"]}335336 return Listing(337 source=self.source_id,338 external_id=slug,339 url=url,340 title=name,341 address=address,342 sector=sector,343 city=city,344 unit_type=unit_type,345 price=price,346 price_label=price_label,347 availability="", # RentCafe n'affiche pas de date par plan348 area_sqft=area_sqft,349 description=" — ".join(desc_parts)[:900],350 amenities=list(payload.get("amenities") or []),351 details=details,352 images=images[: self.max_images],353 )354355 # -- fiche propriété + plans (hors cache seulement) ------------------------356 def _fetch_detail(self, url: str) -> dict:357 """1 à 2 rendus Scrapfly : fiche (adresse, photos, description,358 commodités, plans intégrés) puis /floorplans si nécessaire.359360 La fiche est rendue AVANT tout : sans elle, la ville de la propriété361 est inconnue et l'annonce est écartée.362 """363 if self._renders + 1 > self.max_renders:364 raise _BudgetReached()365 self._renders += 1366367 payload: dict = {"city": "", "sector": "", "address": "",368 "description": "", "amenities": [], "images": [],369 "floorplans": [], "phone": ""}370 html = self._rendered(url, 8000)371 soup = BeautifulSoup(html, "html.parser")372373 addr_el = soup.select_one("[itemprop=address]")374 address = (addr_el.get_text(" ", strip=True) if addr_el else "")375 address = re.sub(r"\s+,", ",", re.sub(r"\s{2,}", " ", address)).strip()376 payload["address"] = address377 payload["city"], payload["sector"] = self._city_sector(address)378 if not payload["city"]:379 return payload # hors Québec : on n'ira pas plus loin380381 for im in soup.select("img[src*='resource.rentcafe.com']"):382 src = im.get("src", "")383 if src and not _SKIP_IMG.search(src) \384 and src not in payload["images"]:385 payload["images"].append(src)386387 paras = [p.get_text(" ", strip=True) for p in soup.find_all("p")]388 paras = [p for p in paras if len(p) > 80]389 if paras:390 payload["description"] = " ".join(paras[:2])[:600]391392 tel = soup.select_one("a[href^='tel:']")393 if tel:394 tm = re.search(r"(\d{3})\D*(\d{3})\D*(\d{4})", tel.get("href", ""))395 if tm:396 payload["phone"] = \397 f"{tm.group(1)}-{tm.group(2)}-{tm.group(3)}"398399 payload["floorplans"] = self._parse_floorplans(soup)400 if not payload["floorplans"]:401 fp_url = re.sub(r"/default(?:\.aspx)?$", "", url).rstrip("/") \402 + "/floorplans"403 if self._renders + 1 <= self.max_renders:404 self._renders += 1405 try:406 payload["floorplans"] = self._parse_floorplans(407 BeautifulSoup(self._rendered(fp_url, 10000),408 "html.parser"))409 except Exception:410 pass411 return payload412413 @staticmethod414 def _parse_floorplans(soup) -> list[dict]:415 """Cartes de plans RentCafe : nom (« 2 Bed 2 Bath »), chambres, pi²416 (borne basse de la fourchette), prix « Starting at » — « Call for417 details » = prix non publié (None, jamais deviné)."""418 plans: list[dict] = []419 for cont in soup.select("div[id^='fp-container-'], div.fp-container"):420 try:421 name_el = cont.select_one(".card-title, h2, h3")422 name = name_el.get_text(" ", strip=True) if name_el else ""423 if not name:424 continue425 text = cont.get_text(" ", strip=True)426 sqft = None427 sm = re.search(r"([\d,]{3,6})\s*(?:-\s*)?(?:[\d,]{3,6}\s*)?"428 r"Sq\.?\s*Ft", text, re.I)429 if sm:430 v = float(sm.group(1).replace(",", ""))431 if 80 <= v <= 20000:432 sqft = v433 price = None434 if re.search(r"(?i)starting at", text):435 pm = _PRICE_RE.search(text)436 if pm:437 v = float(pm.group(0).replace("$", "").replace(",", ""))438 if 100 <= v <= 20000:439 price = v440 unit_type = ""441 bm = re.search(r"(\d)\s*Bed", name, re.I)442 if bm:443 unit_type = normalize_unit_type(f"{bm.group(1)} chambres")444 elif re.search(r"(?i)studio", name):445 unit_type = "Studio"446 if any(p["name"] == name for p in plans):447 continue448 plans.append({"name": name, "sqft": sqft, "price": price,449 "unit_type": unit_type})450 except Exception:451 continue452 return plans453