Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/shdm.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/shdm.py : connecteur SHDM — Société d'habitation et de91# développement de Montréal (shdm.org, logements abordables à Montréal).92# Front Nuxt 3 + WordPress GraphQL : la page /fr/logements-disponibles93# embarque les logements disponibles dans le payload __NUXT_DATA__94# (format « devalue » : tableau plat où les valeurs sont des index).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99import re100101from ..schema import Listing, normalize_unit_type102from .base import BaseConnector103104BASE = "https://www.shdm.org"105LIST_URL = f"{BASE}/fr/logements-disponibles"106107# Champs booléens du CPT « logement » -> libellé de commodité108_AMENITY_FLAGS = {109 "chauffage": "Chauffage inclus",110 "electricite": "Électricité incluse",111 "eauChaude": "Eau chaude incluse",112 "balcon": "Balcon",113 "portePatio": "Porte-patio",114 "plancherBois": "Plancher de bois",115 "deuxEtage": "Sur deux étages",116 "adapte": "Logement adapté",117 "handicape": "Accessible (mobilité réduite)",118 "positionFenetreEst": "Fenêtres à l'est",119 "positionFenetreNord": "Fenêtres au nord",120 "positionFenetreOuest": "Fenêtres à l'ouest",121 "positionFenetreSud": "Fenêtres au sud",122}123124_BEDROOMS_TO_TYPE = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}125126127def _strip_html(s: str) -> str:128 s = re.sub(r"<[^>]+>", " ", s or "")129 s = s.replace("’", "’").replace(" ", " ")130 s = re.sub(r"&[a-z]+;|&#\d+;", " ", s)131 return re.sub(r"\s+", " ", s).strip()132133134class _Devalue:135 """Résolution des références du payload Nuxt 3 (format devalue)."""136137 def __init__(self, data: list):138 self.data = data139140 def resolve(self, ref, seen: frozenset = frozenset()):141 if not isinstance(ref, int) or not (0 <= ref < len(self.data)):142 return ref143 if ref in seen:144 return None145 seen = seen | {ref}146 val = self.data[ref]147 if isinstance(val, dict):148 return {k: self.resolve(v, seen) for k, v in val.items()}149 if isinstance(val, list):150 return [self.resolve(v, seen) for v in val]151 return val152153154class SHDMConnector(BaseConnector):155 source_id = "shdm"156 request_delay = 0.6157158 @staticmethod159 def _media_urls(medias) -> list[str]:160 """[{media:{node:{generic: url, ...}}}] -> URLs pleine taille."""161 urls: list[str] = []162 for m in medias or []:163 node = ((m or {}).get("media") or {}).get("node") or {}164 u = node.get("generic") or node.get("genericDesktop") or ""165 if u:166 urls.append(u)167 return urls168169 def fetch(self) -> list[Listing]:170 listings: list[Listing] = []171 try:172 html = self.get(LIST_URL).text173 except Exception:174 return listings175176 m = re.search(r'id="__NUXT_DATA__"[^>]*>(.*?)</script>', html, re.S)177 if not m:178 return listings179 try:180 data = json.loads(m.group(1))181 except ValueError:182 return listings183 if not isinstance(data, list):184 return listings185 dv = _Devalue(data)186187 seen_ids: set[str] = set()188 for i, raw in enumerate(data):189 if not (isinstance(raw, dict) and "logementFields" in raw190 and "uri" in raw):191 continue192 try:193 node = dv.resolve(i)194 slug = node.get("slug") or ""195 lf = node.get("logementFields") or {}196 if not slug or slug in seen_ids or not isinstance(lf, dict):197 continue198199 imm_nodes = ((lf.get("immeuble") or {}).get("nodes")) or [{}]200 imm = imm_nodes[0] if isinstance(imm_nodes[0], dict) else {}201 bf = imm.get("buildingFields") or {}202203 building_title = (imm.get("title") or "").strip()204 address = (bf.get("adresse") or building_title).strip()205 quartier_nodes = ((bf.get("quartier") or {}).get("nodes")) or []206 sector = (quartier_nodes[0].get("title") or "").strip() \207 if quartier_nodes and isinstance(quartier_nodes[0], dict) else ""208209 unit_no = str(lf.get("numeroLogement") or "").strip()210 typologie = lf.get("typologie") or []211 typ_raw = typologie[0] if typologie else ""212 unit_type = normalize_unit_type(typ_raw) or \213 _BEDROOMS_TO_TYPE.get(lf.get("chambre"), "")214215 price = lf.get("prix")216 price = float(price) if isinstance(price, (int, float)) else None217 price_label = f"{price:,.0f}".replace(",", " ") + " $ / mois" \218 if price else ""219 if re.search(r"stationnement|commercial", typ_raw, re.I):220 continue221222 amenities = [label for key, label in _AMENITY_FLAGS.items()223 if lf.get(key)]224 # nombre de chambres (champ structuré du CPT)225 chambres = lf.get("chambre")226 if isinstance(chambres, int) and chambres > 0:227 amenities.append(f"{chambres} chambre" +228 ("s" if chambres > 1 else ""))229 # clientèle cible (taxonomie « autonomie » : Pour tous, 60+, …)230 auto_edges = ((lf.get("autonomie") or {}).get("edges")) or []231 for edge in auto_edges:232 name = (((edge or {}).get("node")) or {}).get("name") or ""233 if name:234 amenities.append(f"Clientèle : {name}")235 break236237 # étage (champ structuré ; 0 = rez-de-chaussée -> non exposé)238 details: dict = {}239 etage = lf.get("etage")240 if isinstance(etage, int) and etage > 0:241 details["floor"] = etage242 # NB : les booléens d'inclusion du CPT (chauffage, electricite,243 # eauChaude) sont peu fiables à false (cases non cochées alors244 # que la description de l'immeuble dit « inclus ») -> on ne245 # les publie qu'à true, via _AMENITY_FLAGS ci-dessus.246247 # date de disponibilité ISO structurée ("2026-09-01T00:00:00+00:00")248 date_raw = (lf.get("date") or "")[:10]249250 # images : photos du logement + photo(s) de l'immeuble251 images = (self._media_urls(lf.get("medias"))252 + self._media_urls(bf.get("medias")))253254 title = building_title or address255 if unit_no:256 title = f"{title} — app. {unit_no}"257258 # NB : les URI WordPress /fr/logement/<slug> répondent 404259 # (les fiches s'ouvrent en modale) -> on pointe vers la liste,260 # avec le slug en ancre pour garder une URL unique et valide.261 listings.append(Listing(262 source=self.source_id,263 external_id=slug,264 url=f"{LIST_URL}#{slug}",265 title=title,266 address=address,267 sector=sector,268 city="Montréal", # SHDM = société paramunicipale de Mtl269 unit_type=unit_type,270 price=price,271 price_label=price_label,272 availability=date_raw,273 description=_strip_html(bf.get("content") or "")[:600],274 amenities=amenities,275 details=details,276 images=list(dict.fromkeys(u for u in images if u))[:25],277 ))278 seen_ids.add(slug)279 except Exception:280 continue281282 return listings283