Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/capreit.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-2714#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/capreit.py : connecteur CAPREIT (capreit.ca)91# Flux JSON officiel du moteur de recherche (admin-ajax `property_json`)92# filtré sur les villes de la région de Québec ET du Grand Montréal (île de93# Montréal, Laval, Rive-Sud, Rive-Nord proche); les fiches propriétés (rendu94# serveur) fournissent les types d'unités, prix, disponibilités, commodités95# et la galerie photo. Une annonce par type d'unité disponible.96# Exclus : hors-province (province != QC) et villes hors des deux régions.97#98# Expansion Ontario (2026-08) — GATÉE par LOUKA_ONTARIO=1 : le MÊME flux99# admin-ajax contient tout le Canada (~278 propriétés, dont ~108 en ON) ;100# le filtre provincial est purement côté client. Quand la variable101# d'environnement est posée, le fetch inclut AUSSI les villes ontariennes102# (Toronto + arrondissements Scarborough/North York/Etobicoke/York, GTA103# Peel/Halton/Durham/York Region, Ottawa dont Orléans, London,104# Kitchener-Waterloo, Hamilton) avec province="ON" et adresse suffixée105# « ON ». Les fiches détail existent en français (mêmes sélecteurs, URLs106# /fr/) : aucune autre mécanique n'est nécessaire. Sans la variable, le107# comportement est STRICTEMENT identique à la prod QC actuelle.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import hashlib112import os113import re114115from bs4 import BeautifulSoup116117from ..schema import (Listing, infer_city, normalize_unit_type,118 parse_area_sqft, parse_availability_date, parse_price,119 strip_accents)120from .base import BaseConnector121122BASE = "https://www.capreit.ca"123FEED_URL = f"{BASE}/wp-admin/admin-ajax.php?action=property_json&language=fr"124125# Expansion Ontario : opt-in explicite (prod QC inchangée sans la variable)126_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"127128# Villes du flux correspondant à la région Québec/Lévis129_QC_CITIES = {130 "ville de quebec", "quebec", "beauport", "levis", "sainte-foy",131 "charlesbourg", "loretteville", "sillery", "cap-rouge", "val-belair",132 "l-ancienne-lorette", "saint-augustin-de-desmaures", "wendake",133 "saint-romuald", "saint-nicolas", "charny",134}135136# Villes du Grand Montréal : clé normalisée du flux -> nom d'affichage137_GM_CITIES = {138 # Île de Montréal139 "montreal": "Montréal",140 "cote saint-luc": "Côte Saint-Luc",141 "cote-saint-luc": "Côte Saint-Luc",142 "westmount": "Westmount",143 "dorval": "Dorval",144 "pointe-claire": "Pointe-Claire",145 "mont-royal": "Mont-Royal",146 "dollard-des-ormeaux": "Dollard-des-Ormeaux",147 # Laval148 "laval": "Laval",149 # Longueuil / Rive-Sud150 "longueuil": "Longueuil",151 "brossard": "Brossard",152 "boucherville": "Boucherville",153 "saint-lambert": "Saint-Lambert",154 "saint-hubert": "Longueuil",155 "candiac": "Candiac",156 "chateauguay": "Châteauguay",157 # Rive-Nord proche158 "boisbriand": "Boisbriand",159 "repentigny": "Repentigny",160 "terrebonne": "Terrebonne",161 "mascouche": "Mascouche",162 "rosemere": "Rosemère",163 "sainte-therese": "Sainte-Thérèse",164 "blainville": "Blainville",165}166167# Villes ontariennes ciblées (LOUKA_ONTARIO=1) : clé normalisée du flux ->168# nom d'affichage. Le flux CAPREIT distingue les anciens arrondissements de169# Toronto (Scarborough, North York…) : on les garde comme villes, cohérent170# avec l'usage local. Sarnia (hors marchés cibles) volontairement exclue.171_ON_CITIES = {172 # Toronto et arrondissements (ancienne métropole)173 "toronto": "Toronto",174 "scarborough": "Scarborough",175 "north york": "North York",176 "etobicoke": "Etobicoke",177 "york": "York",178 "east york": "East York",179 # GTA — York Region180 "thornhill": "Thornhill",181 "vaughan": "Vaughan",182 "markham": "Markham",183 "richmond hill": "Richmond Hill",184 # GTA — Peel / Halton185 "mississauga": "Mississauga",186 "brampton": "Brampton",187 "oakville": "Oakville",188 "burlington": "Burlington",189 "milton": "Milton",190 # GTA — Durham191 "pickering": "Pickering",192 "ajax": "Ajax",193 "whitby": "Whitby",194 "oshawa": "Oshawa",195 # Ottawa (Orléans/Nepean/Kanata/Gloucester = secteurs d'Ottawa)196 "ottawa": "Ottawa",197 "orleans": "Ottawa",198 "nepean": "Ottawa",199 "kanata": "Ottawa",200 "gloucester": "Ottawa",201 # London202 "london": "London",203 # Hamilton / Kitchener-Waterloo204 "hamilton": "Hamilton",205 "kitchener": "Kitchener",206 "waterloo": "Waterloo",207 "cambridge": "Cambridge",208}209_IMG_RE = re.compile(210 r'https://www\.capreit\.ca/wp-content/uploads/[^"\'\s\\]+'211 r'\.(?:jpg|jpeg|png|webp)', re.I)212_SKIP_IMG = re.compile(213 r"logo|icon|favicon|cropped|-\d{2,4}x\d{2,4}\.|BIL|Phone|badge", re.I)214215216class CapreitConnector(BaseConnector):217 source_id = "capreit"218 request_delay = 0.6219 max_properties = 60 # garde-fou (région de Québec + Grand Montréal)220 max_properties_on = 110 # garde-fou Ontario (budget séparé, LOUKA_ONTARIO=1)221 max_images = 25222223 @staticmethod224 def _city_key(city: str) -> str:225 return strip_accents((city or "").strip().lower())226227 def fetch(self) -> list[Listing]:228 props = self.get(FEED_URL).json()229230 listings: list[Listing] = []231 count = 0 # budget propriétés QC (inchangé)232 count_on = 0 # budget propriétés ON (séparé : ne gruge pas le QC)233 for p in props:234 try:235 prov = (p.get("province") or "").strip().upper()236 ck = self._city_key(p.get("city", ""))237 if prov == "QC":238 if ck not in _QC_CITIES and ck not in _GM_CITIES:239 continue240 if not p.get("has_vacancies"):241 continue242 if count >= self.max_properties:243 if not _ONTARIO:244 break245 continue # mode ON : continuer à balayer l'Ontario246 count += 1247 listings.extend(self._property_listings(p))248 elif _ONTARIO and prov == "ON":249 if ck not in _ON_CITIES:250 continue251 if not p.get("has_vacancies"):252 continue253 if count_on >= self.max_properties_on:254 continue255 count_on += 1256 listings.extend(self._property_listings(p, province="ON"))257 except Exception:258 continue259 return listings260261 def _property_listings(self, p: dict,262 province: str = "QC") -> list[Listing]:263 pid = str(p.get("id"))264 url = p.get("url") or ""265 title = (p.get("title") or "").strip()266 address = (p.get("address") or "").strip()267 feed_city = (p.get("city") or "").strip()268 # adresse complète : rue + ville + province + code postal (du flux) —269 # suffixe « QC » comme avant, « ON » pour les propriétés ontariennes270 postal = (p.get("postal_code") or "").strip()271 if address and feed_city:272 address = f"{address}, {feed_city}" + (f", {province} {postal}"273 if postal else "")274 # coordonnées GPS du flux275 try:276 lat = float(p["latitude"]) if p.get("latitude") else None277 lng = float(p["longitude"]) if p.get("longitude") else None278 except (TypeError, ValueError):279 lat = lng = None280 incentive = (p.get("incentive") or "").strip()281 # secteur : ville précise du flux (ex. Beauport) sinon intersection282 city_key = self._city_key(feed_city)283 if province == "ON":284 # Ontario : la ville du flux est la vraie ville (nom d'affichage285 # de la whitelist) ; secteur = intersection la plus proche, sauf286 # quand la whitelist regroupe (ex. Orléans -> Ottawa) où l'ancien287 # nom de ville devient le secteur.288 city = _ON_CITIES.get(city_key, feed_city)289 if self._city_key(city) == city_key:290 sector = (p.get("nearest_intersection") or "").strip()291 else:292 sector = feed_city293 elif city_key in _GM_CITIES:294 # Grand Montréal : la ville du flux est la vraie ville295 sector = (p.get("nearest_intersection") or "").strip()296 city = _GM_CITIES[city_key]297 elif city_key in ("ville de quebec", "quebec"):298 sector = (p.get("nearest_intersection") or "").strip()299 city = infer_city(sector, default="Québec")300 else:301 sector = feed_city302 city = infer_city(sector, default="Québec")303304 # fiche propriété (rendu serveur) via le cache BD : revisitée305 # seulement quand la ligne du flux change306 feed_key = hashlib.sha1("|".join(307 str(p.get(k)) for k in308 ("id", "min_rent", "earliest_date", "vacancy_message",309 "price_range", "has_vacancies", "units_count", "incentive")310 ).encode("utf-8")).hexdigest()311 d = self.detail(pid, feed_key, lambda: self._fetch_property(url))312 desc = d.get("desc", "")313 amenities = d.get("amenities", [])314 images = d.get("images", [])315 rows = d.get("rows", [])316317 # promotion du flux (ex. « 1 mois de loyer gratuit »)318 if incentive:319 desc = f"Promotion : {incentive}. {desc}".strip()320321 # date de disponibilité structurée du flux (ex. 20260201)322 avail_date = None323 ed = str(p.get("earliest_date") or "")324 if re.fullmatch(r"20\d{6}", ed):325 avail_date = f"{ed[:4]}-{ed[4:6]}-{ed[6:]}"326327 out: list[Listing] = []328 if rows:329 for r in rows:330 ut = normalize_unit_type(r["unit_raw"])331 slug = re.sub(r"[^a-z0-9]+", "-",332 strip_accents(r["unit_raw"].lower())).strip("-")333 out.append(Listing(334 source=self.source_id,335 external_id=f"{pid}-{slug or 'u'}",336 url=url,337 title=f"{title} — {r['unit_raw']}" if r["unit_raw"]338 else title,339 address=address,340 sector=sector,341 city=city,342 province=province,343 unit_type=ut,344 price=parse_price(r["price"]),345 price_label=r["price"],346 availability=r["avail"],347 # date de la ligne (« Disponible 1 sept. ») sinon348 # earliest_date structuré du flux349 availability_date=(parse_availability_date(r["avail"])350 or avail_date),351 # superficie structurée de la ligne (ex. « 875 pi² »)352 area_sqft=parse_area_sqft(r["sqft"]),353 description=desc[:600],354 amenities=amenities,355 images=images,356 lat=lat,357 lng=lng,358 ))359 else:360 # repli : annonce par propriété avec le prix plancher du flux361 min_rent = p.get("min_rent")362 out.append(Listing(363 source=self.source_id,364 external_id=pid,365 url=url,366 title=title,367 address=address,368 sector=sector,369 city=city,370 province=province,371 unit_type=normalize_unit_type(372 (p.get("bedroom_range") or "").split("-")[0]),373 price=float(min_rent) if min_rent else None,374 price_label=p.get("price_range") or "",375 availability=p.get("vacancy_message") or "",376 availability_date=avail_date,377 description=desc,378 amenities=amenities,379 images=images,380 lat=lat,381 lng=lng,382 ))383 return out384385 def _fetch_property(self, url: str) -> dict:386 """Scrape la fiche propriété : galerie, commodités, description,387 et une ligne par type d'unité disponible (« Vos options »)."""388 out: dict = {"desc": "", "amenities": [], "images": [], "rows": []}389 try:390 page = self.get(url).text391 except Exception:392 return out393 soup = BeautifulSoup(page, "html.parser")394395 # galerie photos (héro + blocs JSON de la page)396 images: list[str] = []397 for u in _IMG_RE.findall(page):398 if _SKIP_IMG.search(u):399 continue400 if u not in images:401 images.append(u)402 out["images"] = images[: self.max_images]403404 # commodités (listes à icônes)405 amenities: list[str] = []406 seen = set()407 for li in soup.select("li"):408 if not li.find("div", class_="icon"):409 continue410 t = li.get_text(" ", strip=True)411 if t and len(t) < 60 and t not in seen:412 seen.add(t)413 amenities.append(t)414 out["amenities"] = amenities[:25]415416 # description (« Caractéristiques de l'immeuble »)417 h = soup.find(["h2", "h3"], string=re.compile(418 "Caractéristiques de l['’]immeuble"))419 if h:420 nxt = h.find_next(["p", "div"])421 if nxt:422 out["desc"] = nxt.get_text(" ", strip=True)[:600]423424 # types d'unités disponibles425 for li in soup.select("li.property-options-list-item"):426 avail_el = li.select_one(427 ".property-options-list-item-availability")428 price_el = li.select_one(429 ".property-options-list-item-price")430 details = [d.get_text(" ", strip=True)431 for d in li.select(".property-options-item")]432 unit_raw = details[0] if details else ""433 sqft = details[1] if len(details) > 1 else ""434 if li.get("data-available") == "false":435 continue436 out["rows"].append({437 "unit_raw": unit_raw,438 "sqft": sqft,439 "price": price_el.get_text(" ", strip=True)440 if price_el else "",441 "avail": avail_el.get_text(" ", strip=True)442 if avail_el else "",443 })444 return out445