Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/immeubles_db.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/immeubles_db.py : connecteur Les Immeubles D.B. Busque-Massé91# (immeublesdb.com) — 12 immeubles / ~400 apparts à Sherbrooke, 4 secteurs.92# Site custom PHP (« pm_editor », derrière Cloudflare — le UA de base.py93# passe) : 4 pages statiques /logements-a-louer/secteur-{nord,est,94# centre-ville,ouest}/. Chaque logement offert = une section .container95# avec une cellule galerie (photos /modules/upload/…) et une cellule texte96# (h3 = adresse civique, liste <li> = type, prix « … $ par mois »,97# inclusions). Aucun identifiant publié : external_id = empreinte stable98# (secteur + adresse + ligne de type). Les logements loués sont simplement99# retirés de la page (aucun marqueur « complet » à filtrer).100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://immeublesdb.com"112SECTORS = {113 "secteur-nord": "Nord",114 "secteur-est": "Est",115 "secteur-centre-ville": "Centre-ville",116 "secteur-ouest": "Ouest",117}118119_PRICE_LI = re.compile(r"\d[\d\s]{0,5}\s?\$\s*par mois", re.I)120121122def _clean_price_label(label: str) -> str:123 """« 1 125$ par mois » (espace de milliers) -> compatible parse_price."""124 return re.sub(r"(\d)\s(\d{3})", r"\1\2", label)125126127class ImmeublesDbConnector(BaseConnector):128 source_id = "immeubles_db"129 request_delay = 0.6130131 def fetch(self) -> list[Listing]:132 listings: dict[str, Listing] = {}133 for slug, sector in SECTORS.items():134 try:135 html = self.get(f"{BASE}/logements-a-louer/{slug}/").text136 except Exception:137 continue138 soup = BeautifulSoup(html, "html.parser")139 for container in soup.select("div.container"):140 try:141 lst = self._parse_block(container, sector)142 except Exception:143 continue144 if lst and lst.external_id not in listings:145 listings[lst.external_id] = lst146 return list(listings.values())147148 # -- une section .container = un logement offert --------------------------------149 def _parse_block(self, container, sector: str) -> Listing | None:150 h3 = container.select_one(".cell_container h3")151 ul = container.select_one(".cell_container ul")152 if not (h3 and ul):153 return None154 address_full = re.sub(r"\s+", " ", h3.get_text(" ", strip=True)).strip(" ,")155 lis = [re.sub(r"\s+", " ", li.get_text(" ", strip=True)).strip()156 for li in ul.select("li")]157 lis = [t for t in lis if t]158 if not (address_full and lis):159 return None160161 # « 250, Olivier, Sherbrooke, QC » -> adresse sans la province162 parts = [p.strip() for p in address_full.split(",") if p.strip()]163 address = ", ".join(p for p in parts if p.upper() != "QC")164 city = "Sherbrooke"165166 type_line = lis[0]167 # « 4 CHAMBRES disponibles à partir de 550 $ » = location à la chambre168 # (normalize_unit_type transformerait « 4 chambres » en 6½+)169 if re.search(r"chambres?\s+disponibles?", type_line, re.I):170 unit_type = "Chambre"171 else:172 unit_type = normalize_unit_type(type_line)173 if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",174 unit_type or ""):175 unit_type = ""176177 # prix : première ligne « … $ par mois »178 price = None179 price_label = ""180 for t in lis:181 if _PRICE_LI.search(t):182 price_label = t183 price = parse_price(_clean_price_label(t))184 break185186 # disponibilité : seulement si la source l'écrit (sinon vide)187 availability = ""188 m = re.search(r"libre\s+imm[ée]diatement", " ".join(lis), re.I)189 if m:190 availability = "Libre immédiatement"191192 # photos de la galerie jumelle (chemins relatifs /modules/upload/…)193 images: list[str] = []194 for img in container.select(".galerie_img_block a[href]"):195 href = (img.get("href") or "").strip()196 if href.startswith("/"):197 href = BASE + href198 if href.startswith("http") and href not in images:199 images.append(href)200201 ext_id = hashlib.sha1(202 f"{sector}|{address_full}|{type_line}".encode("utf-8")).hexdigest()[:16]203204 return Listing(205 source=self.source_id,206 external_id=ext_id,207 url=f"{BASE}/logements-a-louer/"208 f"{[k for k, v in SECTORS.items() if v == sector][0]}/",209 title=f"{type_line} — {address}",210 address=address,211 sector=sector,212 city=city,213 unit_type=unit_type,214 price=price,215 price_label=price_label,216 availability=availability,217 description=" | ".join(lis)[:1500],218 images=images[:20],219 )220