Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/akelius.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/akelius.py : connecteur Akelius Residential (rent.akelius.com)91# Page de recherche Canada rendue côté serveur (Angular SSR) : l'état92# TransferState (<script id="akeliusWebsite-state">) contient le JSON complet93# des unités canadiennes (adresse, loyer, pi², chambres, photos). On filtre94# sur le Grand Montréal (Montréal, Westmount, Mont-Royal, Saint-Lambert,95# Greenfield Park) — Toronto/Ottawa/Gatineau exclus.96# Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : quand LOUKA_ONTARIO=1,97# les unités ON de Toronto (+ boroughs North York/Etobicoke…) et d'Ottawa98# sont aussi conservées (province="ON", adresse suffixée « ON ») — le99# TransferState de la page montreal contient déjà TOUTES les unités100# canadiennes, aucune requête de plus. Sans la variable, comportement101# strictement identique (Grand Montréal seulement).102# Chaque unité a aussi un JSON détail (/lettings/marketing/v2/CA/<id>.json)103# avec les keyfacts complets : inclusions (chauffage, eau chaude,104# électricité, internet), électroménagers, animaux, meublé, ascenseur,105# piscine, gym, année de construction, téléphone — visité via le cache106# self.detail() (max ~150 nouveaux fetchs par synchronisation).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import hashlib111import json112import os113import re114115from ..schema import Listing, strip_accents116from .base import BaseConnector117118BASE = "https://rent.akelius.com"119SEARCH_URL = f"{BASE}/en/search/canada/apartment/montreal"120DETAIL_URL = BASE + "/lettings/marketing/v2/CA/{uid}.json"121STATE_RE = re.compile(122 r'<script id="akeliusWebsite-state" type="application/json">(.*?)</script>',123 re.S)124125# Villes admissibles (Grand Montréal) -> (ville normalisée, secteur imposé)126_GM_CITIES = {127 "montreal": ("Montréal", None), # secteur = borough du flux128 "westmount": ("Westmount", "Westmount"),129 "mont-royal": ("Mont-Royal", "Mont-Royal"),130 "saint-lambert": ("Saint-Lambert", "Saint-Lambert"),131 "greenfield park": ("Longueuil", "Greenfield Park"),132}133134# Expansion Ontario 2026-08 — gate : sans LOUKA_ONTARIO=1, GM seulement135_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"136137# Villes admissibles en Ontario (Toronto + boroughs fusionnés, Ottawa)138# -> (ville normalisée, secteur imposé ou None)139_ON_CITIES = {140 "toronto": ("Toronto", None), # secteur = borough du flux141 "north york": ("Toronto", "North York"),142 "east york": ("Toronto", "East York"),143 "etobicoke": ("Toronto", "Etobicoke"),144 "scarborough": ("Toronto", "Scarborough"),145 "york": ("Toronto", "York"),146 "ottawa": ("Ottawa", None),147}148149_BED_TYPES = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}150151# keyfacts booléens du JSON détail -> libellé de commodité (si vrai)152_KF_AMENITIES = {153 "has-air-conditioning": "Climatisation",154 "has-central-air-conditioning": "Climatisation centrale",155 "has-balcony": "Balcon",156 "has-terrace": "Terrasse",157 "has-bicycle-racks": "Supports à vélos",158 "has-blinds": "Stores",159 "has-bosch-built-in-appliances": "Électroménagers encastrés Bosch",160 "has-canada-post-parcel-locker": "Casier à colis Postes Canada",161 "has-central-vacuuming-system": "Aspirateur central",162 "has-concierge": "Concierge",163 "has-dishwasher": "Lave-vaisselle",164 "has-dryer": "Sécheuse",165 "has-washing-machine": "Laveuse",166 "has-washer-dryer": "Laveuse-sécheuse",167 "has-elevator": "Ascenseur",168 "has-fitness-centre": "Salle d'entraînement",169 "has-heated-bathroom-floor": "Plancher de salle de bain chauffant",170 "has-indoor-pool": "Piscine intérieure",171 "has-outdoor-pool": "Piscine extérieure",172 "has-laundry-room": "Buanderie",173 "has-microwave": "Micro-ondes",174 "has-openplan-kitchen": "Cuisine à aire ouverte",175 "has-sauna": "Sauna",176 "has-wine-fridge": "Cellier à vin",177 "is-broadband-included-in-rent": "Internet inclus",178 "is-electricity-included-in-rent": "Électricité incluse",179 "is-gas-included-in-rent": "Gaz inclus",180 "is-heating-included-in-rent": "Chauffage inclus",181 "is-hot-water-included-in-rent": "Eau chaude incluse",182 "is-water-included-in-rent": "Eau incluse",183 "is-refurbished": "Rénové",184 "is-smart-home": "Logement intelligent",185}186187188class _DetailBudget(Exception):189 """Budget de nouvelles pages détail épuisé pour cette synchronisation."""190191192class AkeliusConnector(BaseConnector):193 source_id = "akelius"194 request_delay = 0.6195 max_units = 400 # garde-fou196 max_details = 150 # nouveaux JSON détail max par synchronisation197198 def fetch(self) -> list[Listing]:199 html = self.get(SEARCH_URL).text200 m = STATE_RE.search(html)201 if not m:202 return []203 # TransferState Angular : les guillemets sont encodés « &q; »204 state = json.loads(m.group(1).replace("&q;", '"'))205206 # La clé du cache API est un hash variable : on repère la liste d'unités207 units: list[dict] = []208 for val in state.values():209 body = val.get("b") if isinstance(val, dict) else None210 if (isinstance(body, list) and body211 and isinstance(body[0], dict) and "keyfacts" in body[0]):212 units = body213 break214215 self._detail_fetches = 0216 listings: list[Listing] = []217 for u in units[: self.max_units]:218 try:219 lst = self._unit_listing(u)220 if lst:221 self._enrich(lst, u)222 listings.append(lst)223 except Exception:224 continue225 return listings226227 # -- JSON détail (keyfacts complets) ---------------------------------------228 def _fetch_detail(self, uid: str) -> dict:229 try:230 resp = self.get(DETAIL_URL.format(uid=uid))231 data = json.loads(resp.content.decode("utf-8-sig"))232 except Exception:233 return {}234 if not isinstance(data, dict):235 return {}236 docs = data.get("documents") or []237 images = [d.get("mediumUrl") or d.get("originalImageUrl")238 for d in docs if isinstance(d, dict) and not d.get("isExample")]239 return {240 "keyfacts": data.get("keyfacts") or {},241 "contact": data.get("contactDetails") or {},242 "images": [i for i in images if isinstance(i, str)][:30],243 }244245 def _enrich(self, lst: Listing, u: dict) -> None:246 """Complète l'annonce avec le JSON détail (via cache self.detail)."""247 key = hashlib.sha1(json.dumps(248 {"rent": (u.get("keyfacts") or {}).get("total-rent"),249 "avail": (u.get("keyfacts") or {}).get("available-from-date"),250 "pub": u.get("lastPublishedDate")},251 sort_keys=True).encode("utf-8")).hexdigest()252253 def fetch_fn():254 if self._detail_fetches >= self.max_details:255 raise _DetailBudget()256 self._detail_fetches += 1257 return self._fetch_detail(lst.external_id)258259 try:260 payload = self.detail(lst.external_id, key, fetch_fn)261 except _DetailBudget:262 return263 kf = payload.get("keyfacts") or {}264 if not kf:265 return266267 # commodités (libellés français, seulement les keyfacts vrais)268 for k, label in _KF_AMENITIES.items():269 if kf.get(k) and label not in lst.amenities:270 lst.amenities.append(label)271272 # animaux / meublé (valeurs structurées de la source)273 pets = str(kf.get("pets-allowed") or "").strip().lower()274 if pets == "yes":275 lst.pets = "oui"276 elif pets == "no":277 lst.pets = "non"278 elif pets:279 lst.pets = "conditions"280 furn = str(kf.get("furnished-state") or "").strip().lower()281 if furn == "furnished":282 lst.furnished = True283 elif furn == "unfurnished":284 lst.furnished = False285286 # details structurés (booléens explicites du JSON — jamais devinés)287 details: dict = {}288 inclusions = {}289 for src, dst in (("is-heating-included-in-rent", "heating"),290 ("is-electricity-included-in-rent", "electricity"),291 ("is-hot-water-included-in-rent", "hot_water"),292 ("is-broadband-included-in-rent", "internet")):293 if isinstance(kf.get(src), bool):294 inclusions[dst] = kf[src]295 if inclusions:296 details["inclusions"] = inclusions297 appliances = {}298 if isinstance(kf.get("has-dishwasher"), bool):299 appliances["dishwasher"] = kf["has-dishwasher"]300 if isinstance(kf.get("has-washer-dryer"), bool):301 wd = kf["has-washer-dryer"] or (302 bool(kf.get("has-washing-machine")) and bool(kf.get("has-dryer")))303 appliances["washer_dryer"] = wd304 if appliances:305 details["appliances"] = appliances306 if isinstance(kf.get("has-air-conditioning"), bool):307 details["ac"] = (kf["has-air-conditioning"]308 or bool(kf.get("has-central-air-conditioning")))309 if isinstance(kf.get("has-elevator"), bool):310 details["elevator"] = kf["has-elevator"]311 if isinstance(kf.get("has-balcony"), bool):312 details["balcony"] = kf["has-balcony"] or bool(kf.get("has-terrace"))313 if isinstance(kf.get("has-indoor-pool"), bool) or \314 isinstance(kf.get("has-outdoor-pool"), bool):315 details["pool"] = bool(kf.get("has-indoor-pool")) or \316 bool(kf.get("has-outdoor-pool"))317 if isinstance(kf.get("has-fitness-centre"), bool):318 details["gym"] = kf["has-fitness-centre"]319 if isinstance(kf.get("has-laundry-room"), bool):320 details["laundry"] = kf["has-laundry-room"]321 year = kf.get("construction-year")322 if isinstance(year, int):323 details["construction_year"] = year324 phone = ((payload.get("contact") or {}).get("phoneNumber") or "").strip()325 if phone:326 details["contact"] = {"phone": phone}327 if details:328 lst.details = details329330 # description libre éventuelle (keyfact « free-text »)331 free = str(kf.get("free-text") or "").strip()332 if free:333 lst.description = (lst.description + " — " + free)[:600] \334 if lst.description else free[:600]335336 # photos pleine résolution du détail (600 px au lieu de 400 px)337 if payload.get("images"):338 lst.images = payload["images"][:30]339340 def _unit_listing(self, u: dict) -> Listing | None:341 addr = u.get("address") or {}342 kf = u.get("keyfacts") or {}343 prov = (addr.get("province") or "").upper()344 city_key = strip_accents((addr.get("city") or "").strip().lower())345 if prov == "QC":346 if city_key not in _GM_CITIES:347 return None348 city, forced_sector = _GM_CITIES[city_key]349 elif prov == "ON" and _ONTARIO:350 # Expansion Ontario 2026-08 (gaté LOUKA_ONTARIO)351 if city_key not in _ON_CITIES:352 return None353 city, forced_sector = _ON_CITIES[city_key]354 else:355 return None356 sector = forced_sector or (addr.get("borough") or "").strip()357358 uid = str(u.get("id") or "").strip()359 if not uid:360 return None361 street = (addr.get("streetName") or "").strip()362 postal = (addr.get("postalCode") or "").strip()363364 beds = kf.get("number-of-bedrooms")365 unit_type = _BED_TYPES.get(beds, "") if isinstance(beds, int) else ""366 apt_type = (kf.get("apartment-type") or "").strip()367 if not unit_type and apt_type == "loft":368 unit_type = "Loft"369370 rent = kf.get("total-rent")371 price = float(rent) if isinstance(rent, (int, float)) and rent else None372373 if kf.get("is-available-from-now-on"):374 availability = "Libre maintenant"375 else:376 availability = (kf.get("available-from-date") or "")[:10]377 if availability:378 availability = f"Disponible le {availability}"379380 size = kf.get("unit-size")381 baths = kf.get("number-of-bathrooms")382 floor = kf.get("floor")383 desc_bits = []384 if apt_type:385 desc_bits.append(f"Type : {apt_type}")386 if size:387 desc_bits.append(f"{size} pi²")388 if baths:389 desc_bits.append(f"{baths} salle(s) de bain")390 if floor is not None:391 desc_bits.append(f"étage {floor}")392 if kf.get("free-rent"):393 desc_bits.append(f"promotion : {kf['free-rent']}")394395 amenities = []396 if size:397 amenities.append(f"{size} pi²")398 if baths:399 amenities.append(f"{baths} sdb")400401 images = [i for i in (u.get("imageUrls") or [])402 if isinstance(i, str) and i.startswith("http")][:30]403404 # adresse complète : suffixe « ON » pour l'Ontario (QC inchangé)405 last = f"ON {postal}".strip() if prov == "ON" else postal406 title = f"{street} — unité {uid.split('-')[-1]}" if street else uid407 return Listing(408 source=self.source_id,409 external_id=uid,410 url=f"{BASE}/en/search/canada/detail/{uid}",411 title=title,412 address=", ".join(x for x in [street, city, last] if x),413 sector=sector,414 city=city,415 province=prov,416 unit_type=unit_type,417 price=price,418 price_label=f"{int(rent)} $/mois" if price else "",419 availability=availability,420 description=" — ".join(desc_bits)[:600],421 amenities=amenities,422 images=images,423 lat=addr.get("latitude"),424 lng=addr.get("longitude"),425 )426