Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/lbm.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-09-1314#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/lbm.py : connecteur Groupe Rive-Nord / LBM Gestion Locative91# (grouperivenord.ca — info@lbmgestionlocative.com). Condos locatifs neufs92# « tout inclus » sur le chemin d'Oka : Le 2922 et Le 3215 à93# Sainte-Marthe-sur-le-Lac, Le 3533 (page /le-3537/) à Saint-Joseph-du-Lac.94# WordPress/Divi rendu serveur : les pages projet (liens « le-* » du menu)95# sont des vitrines ; certaines publient des cartes « Modèle N » (type,96# « À partir de X$/m », superficie, chambres, inclusions), les autres97# seulement les typologies offertes (« 4 1/2 et 5 1/2 », 1100 pi²).98# Granularité MODÈLE/TYPOLOGIE par immeuble, prix seulement où publié.99# 2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,100# en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient101# (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA102# (même pattern que boreal_abitibi/citiluxx/cromwell/deschenes_pepin/103# gestion_habitation/gimcote/appartements_rimouski, hébergeur identique).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import os108import re109import time110from urllib.parse import quote111112from ..schema import Listing, normalize_unit_type113from .base import BaseConnector114115BASE = "https://grouperivenord.ca"116117# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)118_SG_MARKER = "/.well-known/sgcaptcha/"119120121def _sg_challenge(resp) -> bool:122 """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""123 if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():124 return True125 return _SG_MARKER in (resp.text or "")[:600]126127PROJECT_RE = re.compile(r'href="(https://grouperivenord\.ca/(le-[\w-]+)/)"')128HERO_RE = re.compile(r"Bienvenue au\s*\|?\s*(\d{2,5}[^|]{0,40}?)\|", re.I)129CITY_RE = re.compile(r"\|\s*((?:Saint|Sainte)e?-[A-Za-zÀ-ü’'-]+(?:-[A-Za-zÀ-ü’'-]+)*)\s*\|")130OCCUP_RE = re.compile(r"Occupation d[èe]s[^|]{0,50}", re.I)131SQFT_RE = re.compile(r"(\d{3,4})\s*pieds?\s*carr[ée]s", re.I)132TYPES_RE = re.compile(r"\d\s*1/2")133PRICE_HERO_RE = re.compile(r"À partir de\s*([\d\s ]{3,7})\$", re.I)134135MODEL_RE = re.compile(136 r"Modèle\s*(\d+)\|\s*\|?Type de logement\s*:\s*([\d\s/½]+)\|"137 r".{0,80}?À partir(?:\s*de)?\|([\d\s ]{3,7})\$\|/\|m"138 r"\|Superficie:\s*([\d\s ]{2,6})\s*pi2"139 r"(?:\|(\d)\s*chambres?)?"140 r"((?:\|[^|]{3,70}){0,10})", re.I | re.S)141142IMG_RE = re.compile(143 r"https://grouperivenord\.ca/wp-content/uploads/[^\"'\s\\)]+?"144 r"\.(?:jpg|jpeg|png|webp)", re.I)145146147def _flat(html: str) -> str:148 txt = re.sub(r"<script.*?</script>", "", html, flags=re.S)149 txt = re.sub(r"<style.*?</style>", "", txt, flags=re.S)150 txt = re.sub(r"<[^>]+>", "|", txt).replace(" ", " ")151 txt = txt.replace("'", "'").replace("’", "'")152 return re.sub(r"[ \t\n]+", " ", re.sub(r"\|+", "|", txt))153154155def _num(txt: str) -> float | None:156 digits = re.sub(r"[^\d]", "", txt or "")157 return float(digits) if digits else None158159160class LbmConnector(BaseConnector):161 source_id = "lbm"162 request_delay = 0.6163164 def _enable_residential_proxy(self) -> bool:165 """Route toute la session via Oxylabs résidentiel CA (session collante)."""166 endpoint = os.environ.get("OXYLABS_PROXY")167 user = os.environ.get("OXYLABS_PROXY_USER")168 pwd = os.environ.get("OXYLABS_PROXY_PASS")169 if not (endpoint and user and pwd):170 return False171 puser = f"{user}-cc-CA-sessid-lbm{int(time.time())}-sesstime-10"172 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"173 self.session.proxies = {"http": proxy, "https": proxy}174 self.session.verify = False # CA MITM du proxy Oxylabs175 return True176177 def _get_html(self, url: str) -> str:178 """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""179 resp = self.get(url)180 if not _sg_challenge(resp):181 return resp.text182 if not self.session.proxies and self._enable_residential_proxy():183 resp = self.get(url)184 if not _sg_challenge(resp):185 return resp.text186 raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")187188 def fetch(self) -> list[Listing]:189 listings: list[Listing] = []190 # échec franc sur challenge/panne (fini le « 0 trouvé ok » silencieux)191 home = self._get_html(BASE + "/")192 pages = list(dict.fromkeys(PROJECT_RE.findall(home)))193 for page_url, slug in pages:194 try:195 html = self._get_html(page_url)196 except Exception:197 continue198 flat = _flat(html)199200 m = HERO_RE.search(flat)201 address = (m.group(1).strip() if m else "").replace("ch. Oka", "chemin d'Oka")202 address = address.replace("Chemin D'Oka", "chemin d'Oka")203 cm = CITY_RE.search(flat)204 city = cm.group(1).strip() if cm else ""205 om = OCCUP_RE.search(flat)206 availability = om.group(0).strip() if om else ""207 images = [u for u in dict.fromkeys(IMG_RE.findall(html))208 if not re.search(r"logo|favicon|icon|-\d+x\d+\.", u,209 re.I)][:20]210211 models = list(MODEL_RE.finditer(flat))212 seen: set[str] = set()213 if models:214 for mm in models:215 n, raw_type, price, sqft, beds, tail = mm.groups()216 ext_id = f"{slug}-modele-{n}"217 if ext_id in seen: # blocs répétés desktop/mobile218 continue219 seen.add(ext_id)220 unit_type = normalize_unit_type(raw_type.strip())221 amenities = [t.strip(" .") for t in tail.split("|")222 if 3 < len(t.strip()) < 70223 and "Modèle" not in t]224 listings.append(Listing(225 source=self.source_id,226 external_id=ext_id,227 url=page_url,228 title=(f"{unit_type} (modèle {n}) — "229 f"{address}, {city}"),230 address=address,231 city=city,232 unit_type=unit_type,233 price=_num(price),234 price_label=f"À partir de {_num(price):.0f} $/mois",235 availability=availability,236 area_sqft=_num(sqft),237 bedrooms=float(beds) if beds else None,238 description=("Condo locatif neuf en formule tout "239 f"inclus au {address}, {city} "240 "(Groupe Rive-Nord / LBM Gestion "241 "Locative)."),242 amenities=amenities[:12],243 details={"model": f"Modèle {n}"},244 images=images,245 ))246 else:247 # vitrine sans modèles : une annonce par typologie citée248 sq = SQFT_RE.search(flat)249 hero_zone = flat[:2500]250 for raw_type in dict.fromkeys(TYPES_RE.findall(hero_zone)):251 unit_type = normalize_unit_type(raw_type)252 ext_id = f"{slug}-{unit_type.replace('½', '.5')}"253 if ext_id in seen:254 continue255 seen.add(ext_id)256 pm = PRICE_HERO_RE.search(hero_zone)257 price = _num(pm.group(1)) if pm else None258 listings.append(Listing(259 source=self.source_id,260 external_id=ext_id,261 url=page_url,262 title=f"{unit_type} — {address}, {city}",263 address=address,264 city=city,265 unit_type=unit_type,266 price=price,267 price_label=(f"À partir de {price:.0f} $/mois"268 if price else ""),269 availability=availability,270 area_sqft=_num(sq.group(1)) if sq else None,271 description=("Condo locatif clé en main, formule "272 f"tout inclus, au {address}, {city} "273 "(Groupe Rive-Nord / LBM Gestion "274 "Locative)."),275 amenities=["Formule tout inclus"],276 images=images,277 ))278 return listings279