Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/labonte.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/labonte.py : connecteur Gestion Labonté (gestionlabonte.com)91# Gestionnaire établi de Sherbrooke (66 ans). Site Wix : la page /logements92# est rendue serveur — répéteur Wix dont chaque item93# (div id="comp-…__<guid>") porte le prix (« À partir de N $/mois »),94# l'adresse (h2), le nombre de pièces, le secteur, la photo et le lien vers95# la page dynamique /logements/<guid> (le GUID du CMS Wix = external_id96# stable). Les fiches détail (via self.detail, cache BD) ajoutent la97# description, les paires « Détails du logement » (secteur, pièces,98# chambres, étage) et l'adresse complète du bloc « Emplacement ». La galerie99# photos des fiches est chargée côté client (pro-gallery, non SSR) : seule100# la photo de la carte est disponible. Aucun statut « loué » affiché — la101# liste ne montre que l'inventaire courant.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price111from .base import BaseConnector112113BASE = "https://www.gestionlabonte.com"114LIST_URL = f"{BASE}/logements"115116_GUID_RE = re.compile(r"/logements/([0-9a-f-]{36})")117118# villes possibles dans l'adresse « Emplacement » (jamais devinées)119_CITY_RE = re.compile(r"\b(Sherbrooke|Magog|East Angus|Lennoxville)\b", re.I)120121122def _clean_unit_type(raw: str) -> str:123 """normalize_unit_type, mais seulement si le motif est net (« 3.5 »,124 « 4,5 », « studio »…) — jamais le texte brut en guise de type."""125 ut = normalize_unit_type(raw)126 if re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison", ut or ""):127 return ut128 return ""129130131def _lines(el) -> list[str]:132 """Lignes de texte nettoyées d'un sous-arbre."""133 out = []134 for raw in el.get_text("\n", strip=True).split("\n"):135 t = re.sub(r"\s+", " ", raw).strip()136 if t:137 out.append(t)138 return out139140141class LabonteConnector(BaseConnector):142 source_id = "labonte"143 request_delay = 0.7144 max_details = 25 # garde-fou fiches détail (vraies requêtes)145146 def fetch(self) -> list[Listing]:147 html = self.get(LIST_URL).text148 soup = BeautifulSoup(html, "html.parser")149150 listings: dict[str, Listing] = {}151 # items du répéteur : conteneurs suffixés par le GUID de l'item CMS152 for item in soup.select('div[id*="__"]'):153 link = item.select_one('a[href*="/logements/"]')154 if not link:155 continue156 m = _GUID_RE.search(link.get("href") or "")157 if not m:158 continue159 guid = m.group(1)160 iid = (item.get("id") or "")161 if not iid.endswith(f"__{guid}") or guid in listings:162 continue # garder le conteneur d'item complet, une fois163164 lines = _lines(item)165 # « À partir de | 1150 | $/mois | 40 rue St-François |166 # Nombre de pièces | 3.5 | Secteur | Centre-ville | En savoir plus »167 h2 = item.select_one("h2")168 address = re.sub(r"\s+", " ", h2.get_text(" ", strip=True)) if h2 else ""169170 price = None171 price_label = ""172 for i, t in enumerate(lines):173 if t.lower().startswith("à partir de") and i + 1 < len(lines):174 amount = lines[i + 1]175 unit = lines[i + 2] if i + 2 < len(lines) else ""176 price_label = f"À partir de {amount} {unit}".strip()177 price = parse_price(f"{amount} $")178 break179180 pieces = sector = ""181 for i, t in enumerate(lines):182 if t.lower().startswith("nombre de pièces") and i + 1 < len(lines):183 pieces = lines[i + 1]184 elif t.lower() == "secteur" and i + 1 < len(lines):185 sector = lines[i + 1]186187 img = item.select_one('img[src*="static.wixstatic.com/media"]')188 images = []189 if img:190 images.append(img["src"].split("/v1/")[0])191192 listings[guid] = Listing(193 source=self.source_id,194 external_id=guid,195 url=f"{BASE}/logements/{guid}",196 title=address or f"Logement {guid[:8]}",197 address=address,198 sector=sector,199 city="Sherbrooke",200 unit_type=_clean_unit_type(pieces),201 price=price,202 price_label=price_label,203 availability="", # non publié par la source204 images=images,205 )206207 # fiches détail (cache BD) : description, chambres/étage, adresse complète208 self._fetched = 0209 for lst in listings.values():210 key = hashlib.sha1(211 f"{lst.title}|{lst.price_label}|{lst.sector}"212 .encode("utf-8")).hexdigest()213 try:214 payload = self.detail(lst.external_id, key,215 lambda u=lst.url: self._fetch_detail(u))216 except Exception:217 continue218 self._apply_detail(lst, payload)219 return list(listings.values())220221 # -- fiche détail (page dynamique Wix) -------------------------------------------222 def _fetch_detail(self, url: str) -> dict:223 if self._fetched >= self.max_details:224 raise RuntimeError("budget de fiches détail atteint")225 self._fetched += 1226 html = self.get(url).text227 soup = BeautifulSoup(html, "html.parser")228 lines = _lines(soup.body or soup)229 out: dict = {}230231 # description : entre « Description » et « Détails du logement »232 try:233 i = lines.index("Description")234 j = lines.index("Détails du logement")235 if 0 <= i < j:236 out["description"] = " ".join(lines[i + 1:j])[:1500]237 except ValueError:238 pass239240 # paires « Détails du logement » : Secteur / pièces / chambres / Étage241 for i, t in enumerate(lines):242 low = t.lower()243 if i + 1 >= len(lines):244 break245 if low == "secteur":246 out["sector"] = lines[i + 1]247 elif low.startswith("nombre de pièces"):248 out["pieces"] = lines[i + 1]249 elif low.startswith("nombre de chambres"):250 out["bedrooms"] = lines[i + 1]251 elif low == "étage":252 out["floor"] = lines[i + 1]253 elif low == "emplacement":254 out["full_address"] = lines[i + 1]255 return out256257 def _apply_detail(self, lst: Listing, d: dict) -> None:258 if not d:259 return260 if d.get("description"):261 lst.description = d["description"]262 if d.get("sector") and not lst.sector:263 lst.sector = d["sector"]264 if d.get("full_address"):265 full = d["full_address"]266 # « 49 Rue King Ouest, Sherbrooke, QC J1H 1P1, Canada »267 lst.address = ", ".join(p.strip() for p in full.split(",")[:2])268 m = _CITY_RE.search(full)269 if m:270 lst.city = m.group(1).title()271 if not lst.unit_type and d.get("pieces"):272 lst.unit_type = _clean_unit_type(d["pieces"])273 details: dict = {}274 if str(d.get("bedrooms") or "").isdigit():275 details["bedrooms"] = int(d["bedrooms"])276 if str(d.get("floor") or "").isdigit():277 details["floor"] = int(d["floor"])278 if details:279 lst.details = {**lst.details, **details}280