Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/immeubles_bc.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_bc.py : connecteur Les Immeubles Beaulieu et Collin91# (immeublesbc.com — Rimouski, 900+ appartements, plus gros gestionnaire du92# Bas-Saint-Laurent). WordPress + thème immobilier Houzez, tout rendu serveur.93# Page /appartements/ : toutes les unités actuellement disponibles (cartes94# Houzez : prix, adresse complète avec code postal, statut, chambres/sdb,95# galerie dans l'attribut data-images). Fiche détail /property/<slug>/ (via96# cache BD) : description, commodités et coordonnées GPS (carte Houzez).97# robots.txt ouvert (Disallow /wp-admin/ seulement), sitemap XML.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import html as htmllib103import json104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://immeublesbc.com"112LIST_URL = f"{BASE}/appartements/"113114# suffixe de redimensionnement WordPress (« -592x444.jpg » -> pleine taille)115_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)116_MAP_LATLNG_RE = re.compile(117 r'"lat"\s*:\s*"(-?\d+\.\d+)"\s*,\s*"lng"\s*:\s*"(-?\d+\.\d+)"')118119120def _clean_price_label(label: str) -> str:121 """'$1,410/mois' -> '$1410/mois' compatible parse_price (virgule = milliers)."""122 return re.sub(r"(\d),(\d{3})", r"\1\2", label)123124125class ImmeublesBCConnector(BaseConnector):126 source_id = "immeubles_bc"127 request_delay = 0.6128 max_details = 60 # garde-fou fiches détail (vraies requêtes par sync)129130 def fetch(self) -> list[Listing]:131 html = self.get(LIST_URL).text132 soup = BeautifulSoup(html, "html.parser")133134 listings: dict[str, Listing] = {}135 for card in soup.select("div.item-listing-wrap"):136 try:137 self._parse_card(card, listings)138 except Exception:139 continue140141 # fiches détail (cache BD) : description, commodités, GPS142 self._fetched = 0143 for lst in listings.values():144 key = hashlib.sha1(145 f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"146 .encode("utf-8")).hexdigest()147 try:148 payload = self.detail(lst.external_id, key,149 lambda u=lst.url: self._fetch_detail(u))150 except Exception:151 continue152 self._apply_detail(lst, payload)153 return list(listings.values())154155 # -- carte Houzez -------------------------------------------------------------156 def _parse_card(self, card, listings: dict[str, Listing]) -> None:157 link = card.select_one("h2.item-title a[href]")158 if not link:159 return160 url = link["href"]161 title = link.get_text(strip=True)162 m = re.search(r"/property/([^/]+)/?", url)163 slug = m.group(1) if m else ""164 listid_el = card.select_one("[data-listid]")165 ext_id = (listid_el.get("data-listid") if listid_el else "") or slug166 if not ext_id or str(ext_id) in listings:167 return168169 # exclusions : commercial / stationnement / rangement170 if re.search(r"commercial|bureau|local|stationnement|garage|entrep[oô]t",171 title, re.I):172 return173174 # statut (« Disponible », « Loué ») — on saute les logements loués175 status_el = card.select_one(".label-status")176 availability = status_el.get_text(strip=True) if status_el else ""177 if re.search(r"lou[ée]", availability, re.I):178 return179180 # adresse complète : « 20 Rue St Laurent E, Rimouski, QC G5L 2C4 »181 addr_el = card.select_one("address.item-address")182 address = addr_el.get_text(" ", strip=True) if addr_el else ""183 city = "Rimouski" # tout le parc est à Rimouski184 parts = [p.strip() for p in address.split(",") if p.strip()]185 for p in parts[1:]:186 if not re.match(r"^(QC|Québec|Quebec|G\d[A-Z])", p, re.I):187 city = re.sub(r"\s+(QC|Québec|Quebec).*$", "", p, flags=re.I).strip() or city188 break189190 price_el = card.select_one("li.item-price")191 price_label = price_el.get_text(strip=True) if price_el else ""192193 # chambres / salles de bain : colonnes structurées de la carte194 amenities: list[str] = []195 beds = ""196 beds_el = card.select_one("li.h-beds .hz-figure")197 if beds_el:198 beds = beds_el.get_text(strip=True)199 if beds:200 amenities.append(f"{beds} chambre(s)")201 baths_el = card.select_one("li.h-baths .hz-figure")202 if baths_el and baths_el.get_text(strip=True):203 amenities.append(f"{baths_el.get_text(strip=True)} salle(s) de bain")204205 # type d'unité dérivé des chambres structurées (0 = Studio, n = (n+2)½)206 unit_type = ""207 if beds.isdigit():208 unit_type = "Studio" if beds == "0" else normalize_unit_type(f"{beds} chambres")209210 # galerie complète : attribut data-images (JSON, URLs redimensionnées)211 images: list[str] = []212 raw = card.get("data-images") or ""213 if raw:214 try:215 entries = json.loads(htmllib.unescape(raw))216 urls = [e.get("image", "") for e in entries if isinstance(e, dict)]217 except Exception:218 urls = re.findall(r"https?:[^\"',\\]+", htmllib.unescape(raw))219 for u in urls:220 u = u.replace("\\/", "/").strip()221 if not u.startswith("http"):222 continue223 u = _SIZE_SUFFIX.sub("", u) # version pleine taille (WordPress)224 if u not in images:225 images.append(u)226 if not images:227 thumb = card.select_one("img.wp-post-image[src]")228 if thumb:229 images = [_SIZE_SUFFIX.sub("", thumb["src"])]230231 listings[str(ext_id)] = Listing(232 source=self.source_id,233 external_id=str(ext_id),234 url=url,235 title=title,236 address=address,237 city=city,238 unit_type=unit_type,239 price=parse_price(_clean_price_label(price_label)),240 price_label=price_label,241 availability=availability,242 amenities=amenities,243 images=images[:30],244 )245246 # -- fiche détail (Houzez) ------------------------------------------------------247 def _fetch_detail(self, url: str) -> dict:248 """Description, commodités (#property-features-wrap) et GPS (carte)."""249 if self._fetched >= self.max_details:250 raise RuntimeError("budget de fiches détail atteint")251 self._fetched += 1252 html = self.get(url).text253 soup = BeautifulSoup(html, "html.parser")254 out: dict = {}255256 desc_el = soup.select_one("#property-description-wrap")257 if desc_el:258 txt = desc_el.get_text("\n", strip=True)259 txt = re.sub(r"^Description\n", "", txt)260 out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1200]261262 out["amenities"] = [a.get_text(" ", strip=True)263 for a in soup.select("#property-features-wrap li")264 if a.get_text(strip=True)][:20]265266 m = _MAP_LATLNG_RE.search(html)267 if m:268 out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))269 return out270271 def _apply_detail(self, lst: Listing, d: dict) -> None:272 """Reporte le payload (frais ou en cache) sur l'annonce."""273 if not d:274 return275 desc = d.get("description") or ""276 # la « description » Houzez du site répète parfois l'adresse : ignorer277 if desc and desc.strip() != lst.address.strip():278 lst.description = desc279 if d.get("amenities"):280 lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))281 if d.get("lat") is not None and d.get("lng") is not None:282 lst.lat, lst.lng = d["lat"], d["lng"]283