Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/lr_gestion.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-08-0914#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/lr_gestion.py : connecteur LR Gestion immobilière / LR Location91# (lrgestion.com ; portail d'annonces lrlocation.ca) — plus gros acteur92# multi-secteurs de l'Outaouais : Gatineau, Hull, Aylmer, Buckingham,93# Cantley, Thurso, Perkins (Val-des-Monts)… Portail RentSync rendu serveur,94# même plateforme que Girescom (girescom.py). Liste /fr/residential : une95# carte par immeuble (adresse avec ville, prix « Louer de », chambres).96# Page immeuble /fr/residential/<slug> : tableau des unités disponibles97# (li.unit-table-desktop__units--unit, colonnes column-field : numéro,98# salles de bain, prix, pi², photos, disponibilité — pas de colonne99# chambres sur ce portail), description « À propos de la propriété »,100# texte « Quartier », téléphone du bureau de location et galerie.101# Une annonce Lou-Ka = une unité. Les immeubles d'Ottawa (Ontario) sont102# exclus ; Hull/Aylmer/Buckingham/Masson-Angers sont des secteurs de103# Gatineau (fusion 2002) -> sector = secteur, city = Gatineau.104# Fiches immeuble via self.detail() (cache BD, max max_details/sync).105# -----------------------------------------------------------------------------106from __future__ import annotations107108import hashlib109import re110111from bs4 import BeautifulSoup112113from ..schema import Listing, parse_price, strip_accents114from .base import BaseConnector115116BASE = "https://www.lrlocation.ca"117LIST_URL = f"{BASE}/fr/residential"118119# secteurs de la ville de Gatineau (fusion municipale de 2002)120_GATINEAU_SECTORS = {"hull", "aylmer", "buckingham", "masson-angers", "masson"}121# hors Québec : parc ontarien du gestionnaire, exclu du périmètre Lou-Ka122_EXCLUDED_CITIES = {"ottawa"}123124125def _city_key(city: str) -> str:126 return re.sub(r"[\s']+", "-", strip_accents(city.strip().lower()))127128129class LRGestionConnector(BaseConnector):130 source_id = "lr_gestion"131 request_delay = 0.6132 max_details = 60 # garde-fou pages immeuble (~48 immeubles QC au 2026-08)133134 def fetch(self) -> list[Listing]:135 # le serveur RentSync n'annonce pas charset=utf-8 : forcer le décodage136 resp = self.get(LIST_URL)137 resp.encoding = "utf-8"138 soup = BeautifulSoup(resp.text, "html.parser")139140 self._fetched = 0141 listings: list[Listing] = []142 for card in soup.select("ul.card-grouping-grid li.card-grouping-grid__item"):143 try:144 listings.extend(self._parse_building(card))145 except Exception:146 continue147 return listings148149 # -- carte immeuble (liste /fr/residential) -----------------------------------150 def _parse_building(self, card) -> list[Listing]:151 link = card.select_one('a[href*="/residential/"]')152 if not link:153 return []154 slug = link["href"].rstrip("/").rsplit("/", 1)[-1]155 url = f"{BASE}/fr/residential/{slug}"156157 title_el = card.select_one(".card-property__title")158 title = title_el.get_text(strip=True) if title_el else slug159 addr_el = card.select_one(".card-property__address--text")160 address = re.sub(r"\s+", " ", addr_el.get_text(" ", strip=True)) \161 if addr_el else ""162163 # « 1072 Boul. Greber, Gatineau, QC » -> ville = avant-dernier segment164 parts = [p.strip() for p in address.split(",") if p.strip()]165 city = parts[-2] if len(parts) >= 2 else ""166 key = _city_key(city)167 if key in _EXCLUDED_CITIES:168 return [] # Ottawa (Ontario) : hors périmètre169 sector = ""170 if key in _GATINEAU_SECTORS:171 sector, city = city, "Gatineau" # secteur de la ville fusionnée172173 rate_el = card.select_one(".card-property__rate-min")174 beds_el = card.select_one(".card-property__beds-content")175 card_sig = (f"{address}|{rate_el.get_text(strip=True) if rate_el else ''}"176 f"|{beds_el.get_text(strip=True) if beds_el else ''}")177178 # page immeuble (cache BD, invalidée quand la carte liste change)179 cache_key = hashlib.sha1(card_sig.encode("utf-8")).hexdigest()180181 def fetch_fn():182 if self._fetched >= self.max_details:183 raise RuntimeError("budget de pages immeuble atteint")184 self._fetched += 1185 return self._fetch_building(url)186187 payload = self.detail(slug, cache_key, fetch_fn)188 if not payload:189 return []190191 building_addr = payload.get("address") or address192 details_base: dict = {"building": title}193 if payload.get("phone"):194 details_base["contact"] = {"phone": payload["phone"]}195196 out: list[Listing] = []197 for u in payload.get("units", []):198 numero = u.get("unit") or ""199 if not numero:200 continue201 # pas de colonne chambres par unité sur ce portail RentSync :202 # seule la salle de bain est structurée (texte source conservé)203 amenities: list[str] = []204 if u.get("bath"):205 amenities.append(u["bath"])206207 area = None208 sqft = re.sub(r"[\s, ]", "", u.get("sqft") or "")209 if re.fullmatch(r"\d{2,5}", sqft) and 80 <= float(sqft) <= 20000:210 area = float(sqft)211212 out.append(Listing(213 source=self.source_id,214 external_id=f"{slug}--{numero}",215 url=url,216 title=f"{title} — unité {numero}",217 address=building_addr,218 sector=sector,219 city=city,220 unit_type="", # chambres non publiées par unité221 price=parse_price(u.get("rate", "")),222 price_label=u.get("rate", ""),223 availability=u.get("availability", ""),224 area_sqft=area,225 description=payload.get("description", ""),226 amenities=amenities,227 details=dict(details_base),228 images=(u.get("photos") or payload.get("gallery") or [])[:20],229 ))230 return out231232 # -- page immeuble --------------------------------------------------------------233 def _fetch_building(self, url: str) -> dict:234 """Payload JSON-sérialisable : unités disponibles + infos immeuble."""235 resp = self.get(url)236 resp.encoding = "utf-8" # charset absent des en-têtes237 html = resp.text238 soup = BeautifulSoup(html, "html.parser")239 payload: dict = {}240241 # adresse de la bannière (identique à la liste, sans code postal)242 addr = soup.select_one(".banner-property__address--text")243 if addr:244 payload["address"] = re.sub(r"\s+", " ",245 addr.get_text(" ", strip=True))246247 # description « À propos de la propriété » + texte « Quartier »248 blocs: list[str] = []249 about = soup.select_one(".property-about__content")250 if about:251 blocs.append(re.sub(r"\s+", " ", about.get_text(" ", strip=True)))252 quartier = soup.select_one(".property-neighbourhood__content")253 if quartier:254 blocs.append("Quartier : " + re.sub(255 r"\s+", " ", quartier.get_text(" ", strip=True)))256 payload["description"] = " | ".join(b for b in blocs if b)[:1500]257258 # téléphone du bureau de location (liens tel:)259 for a in soup.select('a[href^="tel:"]'):260 digits = re.sub(r"\D", "", a["href"])261 if len(digits) >= 10:262 d = digits[-10:]263 payload["phone"] = f"{d[:3]}-{d[3:6]}-{d[6:]}"264 break265266 # galerie de l'immeuble (S3 RentSync) : variante /512/, dédupliquée267 gallery: list[str] = []268 seen: set[str] = set()269 for u in re.findall(270 r"https://s3\.amazonaws\.com/lws_lift/gestion_lr/images/"271 r"gallery/512/[^\"'\s]+", html):272 fname = u.rsplit("/", 1)[-1]273 if fname not in seen:274 seen.add(fname)275 gallery.append(u)276 payload["gallery"] = gallery[:20]277278 # tableau des unités disponibles (colonnes structurées column-field)279 units: list[dict] = []280 for row in soup.select("li.unit-table-desktop__units--unit"):281 cols = {li.get("column-field"): li282 for li in row.select("li[column-field]")}283284 def txt(field: str) -> str:285 el = cols.get(field)286 return re.sub(r"\s+", " ", el.get_text(" ", strip=True)) if el else ""287288 unit = {289 "unit": txt("typeName"),290 "bath": txt("bath"),291 "rate": txt("rate"),292 "sqft": txt("sqFt"),293 "availability": txt("availability"),294 }295 photos_el = cols.get("photos")296 if photos_el:297 unit["photos"] = list(dict.fromkeys(298 a["href"] for a in photos_el.select("a[href^='http']")))299 if unit["unit"] and unit["unit"] != "-":300 # colonnes « - » (non publiées) -> chaîne vide, jamais inventé301 for k, v in list(unit.items()):302 if v == "-":303 unit[k] = ""304 units.append(unit)305 payload["units"] = units306 return payload307