Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/sdg.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0814#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/sdg.py : connecteur SDG Immobilier (sdgimmobilier.ca)91# Site WordPress (thème Houzez) : /appartements-a-louer/ liste des92# immeubles (fiches « immeuble »). Une annonce par immeuble (types93# d'unités affichés, pas de prix ni de disponibilités publiés).94# Galerie via data-images ; fiche : description, caractéristiques,95# bloc adresse structuré (adresse, arrondissement, code postal, ville),96# téléphone (lien tel:). Fiches derrière self.detail(...) (cache BD).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import json102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, infer_city, normalize_unit_type107from .base import BaseConnector108109BASE = "https://www.sdgimmobilier.ca"110LIST_URL = f"{BASE}/appartements-a-louer/"111112IMG_RE = re.compile(113 r"https://www\.sdgimmobilier\.ca/wp-content/uploads/[^\"'\\\s\)]+"114 r"\.(?:jpg|jpeg|png|webp)", re.I)115IMG_NOISE_RE = re.compile(r"logo|favicon|icon|-\d+x\d+\.", re.I)116EXCLUDE_RE = re.compile(r"stationnement|commercial|rangement|entrepos|bureau",117 re.I)118119120class _BudgetReached(Exception):121 """Plafond de requêtes « fiche » atteint pour cette synchronisation."""122123124class SDGConnector(BaseConnector):125 source_id = "sdg"126 request_delay = 0.6127 max_details = 40 # plafond de vraies requêtes fiche par sync128129 def fetch(self) -> list[Listing]:130 html = self.get(LIST_URL).text131 soup = BeautifulSoup(html, "html.parser")132133 listings: dict[str, Listing] = {}134 cards: dict[str, str] = {} # ext_id -> texte de carte (clé de cache)135 for card in soup.select("div.item-listing-wrap[data-hz-id]"):136 try:137 lst = self._parse_card(card)138 except Exception:139 continue140 if lst and lst.external_id not in listings:141 listings[lst.external_id] = lst142 cards[lst.external_id] = card.get_text(" ", strip=True)143144 # Fiches immeuble (cache BD) : description, types, commodités, adresse145 self._fetches = 0146 for lst in listings.values():147 key = hashlib.sha1(148 f"{lst.title}|{cards.get(lst.external_id, '')}"149 .encode("utf-8")).hexdigest()150 try:151 payload = self.detail(152 lst.external_id, key,153 lambda u=lst.url: self._fetch_detail(u))154 except Exception: # _BudgetReached inclus : rien de caché155 continue156 self._apply_detail(lst, payload)157158 return list(listings.values())159160 def _parse_card(self, card) -> Listing | None:161 ext_id = card.get("data-hz-id", "").strip()162 title_a = card.select_one(".item-title a")163 if not ext_id or not title_a:164 return None165 url = title_a.get("href", "")166 if "/immeuble/" not in url:167 return None168 title = title_a.get_text(" ", strip=True)169 if EXCLUDE_RE.search(f"{title} {url}"):170 return None171172 addr_el = card.select_one(".item-address span") or \173 card.select_one(".item-address")174 sector = addr_el.get_text(" ", strip=True) if addr_el else ""175176 # Galerie complète fournie dans l'attribut data-images (JSON)177 images: list[str] = []178 raw = card.get("data-images", "")179 if raw:180 try:181 images = [d.get("image", "") for d in json.loads(raw)182 if d.get("image")]183 except (ValueError, TypeError):184 images = []185 if not images:186 img_el = card.select_one(".listing-thumb img")187 if img_el and (img_el.get("src") or "").startswith("http"):188 images = [img_el["src"]]189190 return Listing(191 source=self.source_id,192 external_id=ext_id,193 url=url,194 title=title,195 address=title if re.match(r"^\d", title) else "",196 sector=sector,197 city=infer_city(sector),198 images=list(dict.fromkeys(images))[:25],199 )200201 def _fetch_detail(self, url: str) -> dict:202 """Télécharge une fiche /immeuble/<slug>/ (appelé seulement hors cache)."""203 if self._fetches >= self.max_details:204 raise _BudgetReached()205 self._fetches += 1206 html = self.get(url).text207 soup = BeautifulSoup(html, "html.parser")208 payload: dict = {}209210 # Description211 desc_el = soup.select_one(".property-description-content") or \212 soup.select_one("#property-description-wrap")213 if desc_el:214 payload["description"] = desc_el.get_text(" ", strip=True)[:600]215216 # Caractéristiques : « Type d'unités: 3 ½ » + commodités217 payload["features"] = [a.get_text(" ", strip=True)218 for a in soup.select("#property-features-wrap li a")]219220 # Bloc « Adresse » Houzez (structuré : adresse, arrondissement,221 # code postal, ville)222 addr: dict = {}223 for row in soup.select("#property-address-wrap .list-lined-item"):224 label = row.find("strong")225 value = row.find("span")226 if not label or not value:227 continue228 key = label.get_text(strip=True).lower().rstrip(" :")229 val = value.get_text(" ", strip=True)230 if val:231 addr[key] = val232 payload["address_block"] = addr233234 # Téléphone du gestionnaire (lien tel: structuré)235 tel = soup.select_one('a[href^="tel:"]')236 if tel:237 m = re.search(r"\(?([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-]?(\d{4})",238 tel.get("href", ""))239 if m:240 payload["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"241242 # Photos de la fiche243 payload["images"] = [u for u in dict.fromkeys(IMG_RE.findall(html))244 if not IMG_NOISE_RE.search(u)]245 return payload246247 @staticmethod248 def _apply_detail(lst: Listing, payload: dict) -> None:249 if payload.get("description"):250 lst.description = payload["description"]251252 amenities = []253 for f in (payload.get("features") or []):254 m = re.search(r"types? d.unités?\s*:?\s*(.+)", f, re.I)255 if m and not lst.unit_type:256 # « 2 ½, 3 ½, 4 ½ et 5 ½ » -> plus petit type (standard Lou-Ka)257 lst.unit_type = normalize_unit_type(m.group(1))258 if f and not m:259 amenities.append(f)260 elif m and "," in m.group(1):261 amenities.append(f) # garder le détail multi-types262 if amenities:263 lst.amenities = amenities[:20]264265 # Adresse structurée : civique + code postal ; arrondissement ; ville266 addr = payload.get("address_block") or {}267 for key, val in addr.items():268 if key.startswith("adresse"):269 lst.address = val270 elif key.startswith("arrondissement") and not lst.sector:271 lst.sector = val272 lst.city = infer_city(val)273 if addr.get("ville"):274 lst.city = addr["ville"] # ville structurée275 if addr.get("code postal") and lst.address \276 and addr["code postal"] not in lst.address:277 lst.address = f"{lst.address}, {addr['code postal']}"278279 if payload.get("phone"):280 lst.details = {**lst.details,281 "contact": {"phone": payload["phone"]}}282283 # Compléter la galerie avec les photos de la fiche284 lst.images = list(dict.fromkeys(285 lst.images + (payload.get("images") or [])))[:25]286