Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/beaudoin.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-2414#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/beaudoin.py : connecteur Société Beaudoin immobilier91# (beaudoinimmobilier.ca — Longueuil, Boucherville, Montréal :92# Anjou, Lachine, Saint-Léonard). Thème WordPress Houzez : les logements93# sont des posts « property » exposés par l'API REST94# (/wp-json/wp/v2/properties) avec prix, adresse géocodée, lat/lng,95# taxonomies (type d'unité, ville, disponibilité, commodités) et96# galerie d'images (IDs de médias résolus via /wp-json/wp/v2/media).97# Le site couvre d'autres régions : seul le Grand Montréal est conservé.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import html as htmllib102import re103104from ..schema import Listing, normalize_unit_type, strip_accents105from .base import BaseConnector106107BASE = "https://www.beaudoinimmobilier.ca"108API = f"{BASE}/index.php/wp-json/wp/v2"109110# Villes admissibles (Grand Montréal) — comparées sans accents, en minuscules.111_ALLOWED_CITIES = (112 "montreal", "longueuil", "boucherville", "brossard", "saint-lambert",113 "laval", "lachine", "anjou", "saint-leonard", "saint-hubert",114)115116117def _clean(txt: str) -> str:118 txt = re.sub(r"<[^>]+>", " ", txt or "")119 return re.sub(r"\s+", " ", htmllib.unescape(txt)).strip()120121122def _additional_features(serialized: str) -> list[str]:123 """Champ Houzez « additional_features » (PHP sérialisé) -> libellés.124125 Paires titre/valeur (« Eau chaude » / « incluse ») -> « Eau chaude incluse ».126 """127 toks = re.findall(r's:\d+:"((?:[^"\\]|\\.)*)"', serialized or "")128 out: list[str] = []129 i = 0130 while True:131 try:132 ti = toks.index("fave_additional_feature_title", i)133 except ValueError:134 break135 title = toks[ti + 1].strip() if ti + 1 < len(toks) else ""136 value = ""137 if ti + 3 < len(toks) and toks[ti + 2] == "fave_additional_feature_value":138 value = toks[ti + 3].strip()139 label = f"{title} {value}".strip()140 if title and label not in out:141 out.append(label)142 i = ti + 2143 return out144145146class BeaudoinConnector(BaseConnector):147 source_id = "beaudoin"148 request_delay = 0.5149 max_pages = 5 # garde-fou (5 x 100 propriétés)150 max_media_ids = 30 # images max par annonce151152 # -- helpers REST ----------------------------------------------------------153 def _terms(self, taxonomy: str) -> dict[int, str]:154 try:155 data = self.get(f"{API}/{taxonomy}?per_page=100").json()156 return {t["id"]: htmllib.unescape(t["name"]) for t in data}157 except Exception:158 return {}159160 def _media_urls(self, ids: list[str]) -> list[str]:161 ids = [i for i in ids if str(i).isdigit()][: self.max_media_ids]162 if not ids:163 return []164 try:165 url = (f"{API}/media?include={','.join(map(str, ids))}"166 f"&per_page=100&_fields=id,source_url")167 data = self.get(url).json()168 by_id = {str(m["id"]): m.get("source_url", "") for m in data}169 return [by_id[str(i)] for i in ids if by_id.get(str(i))]170 except Exception:171 return []172173 @staticmethod174 def _split_city(name: str) -> tuple[str, str]:175 """'Montréal Anjou' -> ('Montréal', 'Anjou') ; 'Longueuil' -> (ville, '')."""176 name = name.strip()177 if strip_accents(name.lower()).startswith("montreal"):178 sector = name[len("Montréal"):].strip(" -–")179 return "Montréal", sector180 return name, ""181182 @staticmethod183 def _city_allowed(name: str) -> bool:184 key = strip_accents(name.lower()).replace(" ", "-")185 return any(tok in key for tok in _ALLOWED_CITIES)186187 # -- fetch ------------------------------------------------------------------188 def fetch(self) -> list[Listing]:189 types = self._terms("property_type")190 statuses = self._terms("property_status")191 cities = self._terms("property_city")192 features = self._terms("property_feature")193 # Sans la taxonomie ville, le filtre Grand Montréal rejette tout :194 # mieux vaut échouer franchement qu'un « succès » à 0 annonce.195 if not cities:196 raise RuntimeError(197 "taxonomie property_city vide/inaccessible — filtre ville impossible")198199 props: list[dict] = []200 for page in range(1, self.max_pages + 1):201 try:202 batch = self.get(203 f"{API}/properties?per_page=100&page={page}").json()204 except Exception:205 if page == 1:206 raise # erreur transitoire ≠ liste vide (évite les faux 0)207 break # fin de pagination (WP renvoie 400 au-delà)208 if not isinstance(batch, list) or not batch:209 break210 props.extend(batch)211 if len(batch) < 100:212 break213214 listings: list[Listing] = []215 for p in props:216 try:217 lst = self._parse_property(p, types, statuses, cities, features)218 except Exception:219 continue220 if lst:221 listings.append(lst)222 return listings223224 def _parse_property(self, p: dict, types: dict, statuses: dict,225 cities: dict, features: dict) -> Listing | None:226 meta = p.get("property_meta") or {}227228 def m1(key: str) -> str:229 v = meta.get(key) or []230 return str(v[0]).strip() if v and v[0] is not None else ""231232 # Ville / secteur (taxonomie property_city, ex. « Montréal Anjou »)233 city_name = next((cities[i] for i in (p.get("property_city") or [])234 if i in cities), "")235 if not city_name or not self._city_allowed(city_name):236 return None # hors Grand Montréal237 city, sector = self._split_city(city_name)238239 title = _clean((p.get("title") or {}).get("rendered") or "")240241 # Adresse géocodée : « 7340, Avenue Guy, Anjou, Montréal, ... Canada »242 map_addr = m1("fave_property_map_address")243 address = ", ".join(s.strip() for s in map_addr.split(",")[:2]) if map_addr else ""244 address = re.sub(r"\s+", " ", address).strip()245246 # Type d'unité (taxonomie « 3 1/2 », « 4 1/2 Penthouse », ...)247 type_name = next((types[i] for i in (p.get("property_type") or [])248 if i in types), "")249 unit_type = normalize_unit_type(type_name)250251 # Prix mensuel (champ Houzez)252 price = None253 price_label = ""254 raw_price = m1("fave_property_price")255 if raw_price:256 try:257 price = float(re.sub(r"[^\d.]", "", raw_price))258 except ValueError:259 price = None260 postfix = m1("fave_property_price_postfix") or "mois"261 price_label = f"{raw_price}$ / {postfix}"262 if price is not None and not (100 <= price <= 20000):263 price = None264265 # Disponibilité (taxonomie property_status, « 08 - Disponible pour août »)266 avail = next((statuses[i] for i in (p.get("property_status") or [])267 if i in statuses), "")268 availability = re.sub(r"^\d+\s*-\s*", "", avail)269270 amenities = [features[i] for i in (p.get("property_feature") or [])271 if i in features]272 # « Caractéristiques additionnelles » Houzez (PHP sérialisé) :273 # Eau chaude incluse, Lave-vaisselle inclus, Chiens et chats acceptés…274 for label in _additional_features(m1("additional_features")):275 if label not in amenities:276 amenities.append(label)277278 # Superficie structurée (fave_property_size, préfixe « Pieds carrés »)279 area_sqft = None280 raw_size = m1("fave_property_size")281 size_prefix = m1("fave_property_size_prefix").lower()282 if raw_size:283 try:284 val = float(raw_size.replace(",", "."))285 except ValueError:286 val = None287 if val and 80 <= val <= 20000 and (288 not size_prefix or "pied" in size_prefix289 or "pi" in size_prefix or "sq" in size_prefix):290 area_sqft = val291292 # Chambres / salles de bain (champs Houzez) -> commodités affichables293 beds = m1("fave_property_bedrooms")294 baths = m1("fave_property_bathrooms")295 if beds.isdigit() and int(beds) > 0:296 amenities.append(f"{beds} chambre{'s' if int(beds) > 1 else ''}")297 if baths.isdigit() and int(baths) > 0:298 amenities.append(299 f"{baths} salle{'s' if int(baths) > 1 else ''} de bain")300301 # Coordonnées302 lat = lng = None303 try:304 lat = float(m1("houzez_geolocation_lat"))305 lng = float(m1("houzez_geolocation_long"))306 except (ValueError, TypeError):307 lat = lng = None308309 # Galerie d'images (IDs de médias -> URLs)310 images = self._media_urls(meta.get("fave_property_images") or [])311 if not images:312 thumb = m1("_thumbnail_id")313 if thumb:314 images = self._media_urls([thumb])315316 description = _clean((p.get("content") or {}).get("rendered") or "")[:600]317318 return Listing(319 source=self.source_id,320 external_id=str(p.get("id")),321 url=p.get("link") or "",322 title=title or f"Logement {p.get('id')}",323 address=address,324 sector=sector,325 city=city,326 unit_type=unit_type,327 price=price,328 price_label=price_label,329 availability=availability,330 area_sqft=area_sqft,331 description=description,332 amenities=amenities,333 images=images,334 lat=lat,335 lng=lng,336 )337