Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/desmarais.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/desmarais.py : connecteur Immeubles Desmarais (immeublesdesmarais.ca)91# Gestionnaire historique de Gatineau (Hull, Aylmer, Buckingham). Site PHP92# custom encodé ISO-8859-1, rendu CÔTÉ SERVEUR : la page /logements liste93# les cartes (titre, secteur, chambres, superficie, type, prix « À partir94# de ») avec pagination ?entity=logements&page=N. Le script de la carte95# Google (showAddress) publie en plus l'adresse civique + code postal et le96# lien canonique /logements/<id>/<slug> de chaque annonce.97# La fiche détail ajoute la date de disponibilité, la description complète98# et la galerie (/upload/logements/<id>/NN.jpg) — via self.detail() (cache99# BD) avec plafond par sync. Les locaux commerciaux vivent sous /locaux100# (entité distincte) et ne sont donc jamais ramassés.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_area_sqft, parse_price110from .base import BaseConnector111112BASE = "https://www.immeublesdesmarais.ca"113LIST_URL = f"{BASE}/logements"114115# secteurs de l'agglomération de Gatineau (le site filtre par ces 4 secteurs)116_SECTEURS = {"hull": "Hull", "aylmer": "Aylmer", "buckingham": "Buckingham",117 "gatineau": ""}118119# showAddress(map, '<adresse civique>', '...href=\"/logements/<id>/<slug>\"...')120_MAP_RE = re.compile(121 r"showAddress\(map,\s*'([^']*)',\s*'.*?href=\\\"/logements/(\d+)/([^/\\\"]+)"122)123124125def _clean_txt(s: str) -> str:126 return re.sub(r"\s+", " ", (s or "").strip())127128129class DesmaraisConnector(BaseConnector):130 source_id = "desmarais"131 request_delay = 1.0132 max_pages = 6 # garde-fou de pagination (12 annonces = 2 pages)133 max_details = 20 # fiches détail réellement visitées par sync134 max_images = 20135136 def __init__(self) -> None:137 super().__init__()138 self._detail_calls = 0139140 # -- helpers ---------------------------------------------------------------141 def _html(self, url: str) -> str:142 """Le site est encodé ISO-8859-1 (meta charset) : forcer le décodage,143 sinon les accents deviennent mojibake selon l'en-tête du serveur."""144 resp = self.get(url)145 resp.encoding = "iso-8859-1"146 return resp.text147148 @staticmethod149 def _city_sector(raw: str) -> tuple[str, str]:150 """« Hull (Québec) J8X 4G9 » -> ('Gatineau', 'Hull') ;151 « Gatineau (Québec) » -> ('Gatineau', '')."""152 base = re.split(r"[(]", _clean_txt(raw))[0].strip()153 key = base.lower()154 if key in _SECTEURS:155 return "Gatineau", _SECTEURS[key]156 return base, "" # imprévu : on garde le libellé source tel quel157158 @staticmethod159 def _unit_type(beds: str) -> str:160 """Nombre de chambres de la carte : « bach » (garçonnière) -> Studio,161 sinon « N chambres » normalisé par la couche commune."""162 b = _clean_txt(beds).lower()163 if b.startswith("bach") or "garconni" in b or "garçonni" in b:164 return "Studio"165 m = re.match(r"^(\d+)", b)166 return normalize_unit_type(f"{m.group(1)} chambres") if m else ""167168 # -- fiche détail ------------------------------------------------------------169 def _fetch_detail(self, url: str) -> dict:170 """Date de disponibilité, description complète et galerie photos."""171 self._detail_calls += 1172 html = self._html(url)173 soup = BeautifulSoup(html, "html.parser")174 out: dict = {}175176 td = soup.find("td", string=re.compile(r"Date de disponibilit"))177 if td:178 nxt = td.find_next_sibling("td")179 if nxt:180 out["availability"] = _clean_txt(nxt.get_text(" ", strip=True))181182 desc = soup.select_one("#detailRight p.greyText")183 if desc:184 txt = desc.get_text("\n", strip=True)185 out["description"] = re.sub(r"\s*\n\s*", " ", txt).strip()[:2000]186187 images: list[str] = []188 for a in soup.select("a.glightbox[href^='/upload/']"):189 u = BASE + a["href"]190 if u not in images:191 images.append(u)192 out["images"] = images193 return out194195 # -- fetch -----------------------------------------------------------------196 def fetch(self) -> list[Listing]:197 listings: dict[str, Listing] = {}198 canon: dict[str, tuple[str, str]] = {} # id -> (adresse civique, slug)199200 for page in range(1, self.max_pages + 1):201 url = LIST_URL if page == 1 else f"{LIST_URL}?entity=logements&page={page}"202 try:203 html = self._html(url)204 except Exception:205 break206 # adresses civiques + liens canoniques publiés par la carte Google207 for addr, num, slug in _MAP_RE.findall(html):208 canon.setdefault(num, (_clean_txt(addr), slug))209 soup = BeautifulSoup(html, "html.parser")210 cards = soup.select("div.infoLogement")211 if not cards:212 break213 before = len(listings)214 for card in cards:215 try:216 self._parse_card(card, listings)217 except Exception:218 continue219 if len(listings) == before: # page sans nouveauté = fin220 break221222 # adresse civique (carte Google) + fiche détail (cache BD)223 for ext, lst in listings.items():224 addr, slug = canon.get(ext, ("", ""))225 if addr:226 # « 215 Rue de Canadel Gatineau, Québec J8T 8C3, J8T 8C3 » ->227 # partie civique seulement (la ville est déjà normalisée)228 civic = addr.split(",")[0].strip()229 civic = re.sub(r"\s+(Gatineau|Hull|Aylmer|Buckingham)$", "",230 civic, flags=re.I)231 lst.address = f"{civic}, {lst.city}" if civic else ""232 if slug:233 lst.url = f"{BASE}/logements/{ext}/{slug}"234235 key = hashlib.sha1(236 f"{lst.title}|{lst.price_label}|{lst.description}"237 .encode("utf-8")).hexdigest()[:20]238 if self._detail_calls >= self.max_details:239 continue240 try:241 payload = self.detail(ext, key,242 lambda u=lst.url: self._fetch_detail(u))243 except Exception:244 continue245 if payload.get("availability"):246 lst.availability = payload["availability"]247 if payload.get("description"):248 lst.description = payload["description"]249 for img in payload.get("images") or []:250 if img not in lst.images and len(lst.images) < self.max_images:251 lst.images.append(img)252253 return list(listings.values())254255 # -- carte de la liste -------------------------------------------------------256 def _parse_card(self, card, listings: dict[str, Listing]) -> None:257 link = card.select_one("a[href*='details.php']")258 if not link:259 return260 m = re.search(r"[?&]id=(\d+)", link.get("href", ""))261 if not m:262 return263 ext = m.group(1)264 if ext in listings:265 return266267 top = card.select_one(".logementImageTop")268 spans = top.select("span") if top else []269 title = _clean_txt(spans[0].get_text(" ", strip=True)) if spans else ""270 loc_raw = _clean_txt(spans[1].get_text(" ", strip=True)) if len(spans) > 1 else ""271 city, sector = self._city_sector(loc_raw)272273 # type d'immeuble (Appartement / Condo / Maison) + prix « À partir de »274 prix_sec = card.select_one(".logementPrixSection")275 btype, price_label = "", ""276 if prix_sec:277 st = prix_sec.select_one("span strong")278 btype = _clean_txt(st.get_text(strip=True)) if st else ""279 pr = prix_sec.select_one("span.pull-right")280 price_label = _clean_txt(pr.get_text(" ", strip=True)) if pr else ""281 if re.search(r"commercial|local", btype, re.I):282 return # résidentiel seulement283284 # chambres + superficie (blocs à icônes de la carte)285 beds = sqft = ""286 for div in card.select(".logementImageBot strong, .logementImageBotInfoBox strong"):287 t = _clean_txt(div.get_text(strip=True))288 if "pi²" in t or "pi2" in t.lower():289 sqft = sqft or t290 elif t:291 beds = beds or t292 if not beds: # repli : blocs « <strong>2</strong> chambres »293 m2 = re.search(r"<strong>\s*(bach|\d+)\s*</strong>\s*chambre",294 str(card), re.I)295 if m2:296 beds = m2.group(1)297 m3 = re.search(r"<strong>\s*([\d\s]+pi²)\s*</strong>", str(card))298 if m3 and not sqft:299 sqft = _clean_txt(m3.group(1))300301 # extrait de description de la carte (remplacé par la fiche détail)302 snippet_el = card.select_one(".contentLogementInt")303 snippet = _clean_txt(snippet_el.get_text(" ", strip=True)) if snippet_el else ""304 snippet = re.sub(r"\(\.\.\.\)$", "…", snippet)305306 img_el = card.select_one(".logementImage[style]")307 images: list[str] = []308 if img_el:309 m4 = re.search(r"url\(([^)]+)\)", img_el.get("style", ""))310 if m4:311 images.append(BASE + m4.group(1).strip("'\" "))312313 details: dict = {}314 if btype:315 details["building_type"] = btype316317 listings[ext] = Listing(318 source=self.source_id,319 external_id=ext,320 url=f"{BASE}/logements/{ext}/",321 title=title,322 sector=sector,323 city=city,324 unit_type=self._unit_type(beds),325 price=parse_price(price_label),326 price_label=price_label,327 area_sqft=parse_area_sqft(sqft),328 description=snippet,329 details=details,330 images=images,331 )332