Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/heafey.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-08-1814#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/heafey.py : connecteur Groupe Heafey (Gatineau, secteur Hull)91# Le résidentiel du groupe vit sur un micro-site WordPress par projet, comme92# Immostar (immostar.py) :93# - Le We 2 et Le We 3 (lewe2.ca) -> sélecteur d'unités « Resimo »94# - Loggia sur le Parc (loggiasurleparc.com) -> même sélecteur Resimo95# La page /plans/ de chaque site intègre en iframe l'application Resimo96# (allinone-corsim-*.prod.resimo.io) dont la configuration publique donne97# l'URL d'inventaire, le jeton d'intégration et la liste des immeubles ;98# cet endpoint renvoie un JSON par immeuble : n° d'unité, superficie (pi²),99# nombre de chambres, statut (available / reserved / sold) et, avec100# additional_fields, le plan d'étage (pdf_url) et le lien de location.101# La découverte se fait à chaque sync (aucun jeton codé en dur) : 1 requête102# /plans/ + 1 requête app + 1 requête inventaire par site.103# Une annonce = une unité DISPONIBLE. Le paramètre Resimo `showPrice` est à104# false sur les trois projets, mais le PRIX PAR UNITÉ est publié par le105# back-office DashQ : le `web_url` de chaque unité pointe vers106# myapartment.rent (SPA DashQ) avec bpi = identifiant public de l'immeuble ;107# l'API publique de cette SPA (webapi.myapartment.rent108# /api/rental-application-request/getRentalRequestListing?publicIdentifier=109# <bpi>) renvoie TOUTES les unités offertes : loyer (unitPrice), salles de110# bain, date de disponibilité (madeReadyDate), adresse civique exacte et111# code postal (c'est ainsi qu'on apprend l'adresse du We 3 : 82, rue112# Saint-Rédempteur). 1 requête DashQ par immeuble (3 au total), fusionnée113# par numéro d'unité. Une unité absente de DashQ reste sans prix — rien114# n'est inventé. GPS : non publié par la source (l'adresse civique propre115# alimente le géocodeur maison).116# -----------------------------------------------------------------------------117from __future__ import annotations118119import re120from urllib.parse import parse_qs, quote, urljoin, urlparse121122from bs4 import BeautifulSoup123124from ..schema import Listing, normalize_unit_type125from .base import BaseConnector126127# Projets (un micro-site peut porter deux immeubles : We 2 et We 3)128PROJECTS = [129 {"id": "we2", "name": "Le We 2", "building": "Le We2",130 "site": "https://lewe2.ca/", "plans": "plans/",131 "address": "45, rue Eddy, Gatineau, QC J8X 2V8", "sector": "Hull",132 "pages": ("unites-vedettes/", "espaces-communs/")},133 # We 3 : tour voisine, livraison septembre 2026 ; son adresse civique134 # propre n'est pas publiée sur le site (seul le bureau de location135 # 45, rue Eddy l'est) -> adresse laissée vide plutôt qu'inventée.136 {"id": "we3", "name": "Le We 3", "building": "Le We3",137 "site": "https://lewe2.ca/", "plans": "plans/",138 "address": "", "sector": "Hull",139 "pages": ("unites-vedettes/", "espaces-communs/")},140 {"id": "loggia", "name": "Loggia sur le Parc",141 "building": "LOGGIA Sur le Parc",142 "site": "https://loggiasurleparc.com/", "plans": "plans/",143 "address": "401, rue Champlain, Gatineau, QC J8X 0B1", "sector": "Hull",144 "pages": ("unites-vedettes/", "espaces-communs/")},145]146147_APP_RE = re.compile(r"https://[a-z0-9.-]*resimo\.io/[^\"']*")148_API_RE = re.compile(r"url:\s*'(https://api\.resimo[^']+/apartments/?)'")149_TOKEN_RE = re.compile(r"token:\s*'([^']+)'")150_BUILDINGS_RE = re.compile(r"buildingList:\s*\[([^\]]*)\]")151_FIELDS_RE = re.compile(r"additionalFields:\s*\[([^\]]*)\]")152_IMG_RE = re.compile(153 r'https?://[^"\'\s\)]+/wp-content/uploads/[^"\'\s\)]+\.(?:jpg|jpeg|webp)',154 re.I)155_SKIP_IMG = re.compile(156 r"logo|icon|favicon|plan|selecteur|-\d{2,4}x\d{2,4}\.", re.I)157158# API publique DashQ (myapartment.rent) : unités offertes d'un immeuble159DASHQ_LISTING_API = ("https://webapi.myapartment.rent/api/"160 "rental-application-request/getRentalRequestListing")161# « 3 1/2 TYPE C.2 » (nom du plan DashQ) -> typologie n½162_PLAN_DEMI_RE = re.compile(r"\b(\d)\s+1/2\b")163164165def _unit_key(num: str) -> str:166 """Numéro d'unité normalisé pour la fusion Resimo/DashQ167 (« 0411 » et « 411 » désignent la même unité)."""168 n = str(num or "").strip().lstrip("0")169 return n or "0"170171172class HeafeyConnector(BaseConnector):173 source_id = "heafey"174 request_delay = 0.6175 max_images = 10176 max_units = 400 # garde-fou (We 3 seul compte 342 unités)177178 # -- découverte de l'inventaire Resimo -------------------------------------179 def _inventory(self, site: str, plans_path: str) -> dict[str, list[dict]]:180 """Inventaire par immeuble : {'Le We2': [unités...], ...}.181182 Suit la chaîne publiée par le site : page /plans/ -> iframe de183 l'application Resimo -> configuration (URL, jeton, immeubles) -> JSON.184 """185 html = self.get(urljoin(site, plans_path)).text186 soup = BeautifulSoup(html, "html.parser")187 app_url = ""188 for frame in soup.find_all("iframe"):189 for attr in ("data-lazy-src", "src", "data-src"):190 cand = frame.get(attr) or ""191 if "resimo.io" in cand:192 app_url = cand.split("#")[0]193 break194 if app_url:195 break196 if not app_url:197 m = _APP_RE.search(html)198 app_url = m.group(0).split("#")[0] if m else ""199 if not app_url:200 return {}201202 cfg = self.get(app_url).text203 m_api, m_tok = _API_RE.search(cfg), _TOKEN_RE.search(cfg)204 if not (m_api and m_tok):205 return {}206 m_bld = _BUILDINGS_RE.search(cfg)207 m_fld = _FIELDS_RE.search(cfg)208 buildings = re.findall(r"'([^']+)'", m_bld.group(1)) if m_bld else []209 fields = re.findall(r"'([^']+)'", m_fld.group(1)) if m_fld else []210 params = {"token": m_tok.group(1)}211 if buildings:212 params["building_list"] = ";".join(buildings)213 if fields:214 params["additional_fields"] = ",".join(fields)215216 data = self.get(m_api.group(1), params=params).json()217 out: dict[str, list[dict]] = {}218 for bloc in data if isinstance(data, list) else []:219 num = str(bloc.get("number") or "")220 if num:221 out[num] = list(bloc.get("apartments") or [])222 return out223224 # -- prix par unité (back-office DashQ / myapartment.rent) -----------------225 def _dashq_listing(self, bpi: str) -> dict[str, dict]:226 """Unités OFFERTES d'un immeuble chez DashQ : {n° unité: fiche}.227228 La fiche porte unitPrice (loyer mensuel), unitBathrooms, unitBedrooms,229 madeReadyDate, streetAddress (« 1005 45 rue Eddy »), postalCode et le230 nom du plan (« 3 1/2 TYPE C.2 »). Appelée une fois par immeuble.231 """232 try:233 data = self.get(DASHQ_LISTING_API,234 params={"publicIdentifier": bpi}).json()235 except Exception:236 return {}237 d = (data or {}).get("data") or {}238 out: dict[str, dict] = {}239 for unit in d.get("listings") or []:240 if unit.get("unitIdentifier") is not None:241 out[_unit_key(unit.get("unitIdentifier"))] = unit242 return out243244 @staticmethod245 def _apply_dashq(lst: Listing, unit: dict) -> None:246 """Fusionne la fiche DashQ d'une unité dans le Listing Resimo."""247 try:248 price = float(unit.get("unitPrice") or 0)249 except (TypeError, ValueError):250 price = 0.0251 if 100 <= price <= 20000:252 lst.price = price253 lst.price_label = f"{price:,.0f} $/mois".replace(",", " ")254 try:255 sdb = float(unit.get("unitBathrooms") or 0)256 if sdb:257 lst.bathrooms = sdb258 except (TypeError, ValueError):259 pass260 made = str(unit.get("madeReadyDate") or "")[:10]261 if re.fullmatch(r"\d{4}-\d{2}-\d{2}", made):262 lst.availability = f"Disponible le {made}"263 lst.availability_date = made264 # adresse civique exacte : « 1005 45 rue Eddy » -> rue sans le n°265 # d'unité, complétée du code postal (le n° d'unité reste en details)266 street = str(unit.get("streetAddress") or "").strip().rstrip(".")267 num = str(unit.get("unitIdentifier") or "").strip()268 if street and num and street.startswith(num + " "):269 street = street[len(num):].strip()270 postal = str(unit.get("postalCode") or "").strip()271 if street and not lst.address:272 lst.address = f"{street}, Gatineau, QC {postal}".strip()273 if postal:274 lst.details.setdefault("Code postal", postal)275 # nom du plan (« 3 1/2 TYPE C.2 ») : typologie n½ + référence du plan276 for fp in unit.get("floorPlans") or []:277 friendly = str(fp.get("friendlyName") or "").strip()278 if friendly:279 lst.details.setdefault("Plan", friendly)280 m = _PLAN_DEMI_RE.search(friendly)281 if m and not lst.unit_type:282 lst.unit_type = f"{m.group(1)}½"283 break284285 # -- pages du micro-site ---------------------------------------------------286 def _site_images(self, site: str) -> list[str]:287 """Photos du projet (uploads jpg/webp de l'accueil et de la galerie)."""288 imgs: list[str] = []289 for page in ("", "galerie/"):290 try:291 html = self.get(urljoin(site, page)).text292 except Exception:293 continue294 for u in dict.fromkeys(_IMG_RE.findall(html)):295 if not _SKIP_IMG.search(u) and u not in imgs:296 imgs.append(u)297 return imgs[: self.max_images]298299 def _site_amenities(self, site: str, pages: tuple[str, ...]) -> list[str]:300 """Inclusions et espaces communs tels qu'écrits par le promoteur :301 phrase « Inclusions : … » des unités vedettes (identique pour tout le302 projet) + titres des espaces communs."""303 items: list[str] = []304 for page in pages:305 try:306 html = self.get(urljoin(site, page)).text307 except Exception:308 continue309 soup = BeautifulSoup(html, "html.parser")310 text = soup.get_text("\n", strip=True)311 for m in re.finditer(r"Inclusions\s*:\s*\n?([^\n]{10,300})", text):312 for part in re.split(r"[,;]|\bet\b", m.group(1)):313 t = part.strip(" . ")314 if 3 <= len(t) <= 80 and t not in items:315 items.append(t)316 for h in soup.select("h2, h3"):317 t = re.sub(r"\s+", " ", h.get_text(" ", strip=True)).strip()318 # les titres de TYPOLOGIE (« 2 chambres, 1 salle de bain »)319 # décrivent une unité, pas un espace commun320 if re.search(r"(?i)chambres?\b|salle de bain|\d\s*½", t):321 continue322 if (3 <= len(t) <= 60 and t not in items323 and re.search(r"(?i)piscine|salle|terrasse|salon|toit"324 r"|sauna|espace|gym|ascenseur|lounge"325 r"|yoga|stationnement", t)):326 items.append(t)327 return items[:30]328329 # -- fetch -----------------------------------------------------------------330 def fetch(self) -> list[Listing]:331 inventories: dict[str, dict[str, list[dict]]] = {}332 images: dict[str, list[str]] = {}333 amenities: dict[str, list[str]] = {}334 self._dashq_cache: dict[str, dict[str, dict]] = {}335336 listings: list[Listing] = []337 for proj in PROJECTS:338 site = proj["site"]339 try:340 if site not in inventories:341 inventories[site] = self._inventory(site, proj["plans"])342 images[site] = self._site_images(site)343 amenities[site] = self._site_amenities(site, proj["pages"])344 units = inventories[site].get(proj["building"], [])345 except Exception:346 continue347348 plans_url = urljoin(site, proj["plans"])349 # prix/adresse/dispo par unité : le bpi (identifiant public de350 # l'immeuble chez DashQ) est porté par le web_url des unités351 bpi = ""352 for unit in units:353 q = parse_qs(urlparse(str(unit.get("webUrl") or "")).query)354 bpi = (q.get("bpi") or [""])[0]355 if bpi:356 break357 dashq = self._dashq_cache.setdefault(358 bpi, self._dashq_listing(bpi) if bpi else {})359360 for unit in units[: self.max_units]:361 try:362 if str(unit.get("status") or "").lower() != "available":363 continue364 num = str(unit.get("name") or unit.get("mappingName") or "")365 if not num:366 continue367 area = None368 try:369 val = float(unit.get("area") or 0)370 area = val if 80 <= val <= 20000 else None371 except (TypeError, ValueError):372 area = None373 rooms = unit.get("rooms")374 unit_type = (normalize_unit_type(f"{int(rooms)} chambres")375 if isinstance(rooms, (int, float)) and rooms376 else "")377378 imgs = list(images.get(site, []))379 plan = str(unit.get("pdfUrl") or "")380 if plan.startswith("http"):381 # les noms de fichiers Resimo contiennent des espaces382 imgs.insert(0, quote(plan, safe=":/?=&%"))383384 desc = " — ".join(x for x in [385 f"{int(rooms)} chambre(s)"386 if isinstance(rooms, (int, float)) and rooms else "",387 f"{area:.0f} pi²" if area else "",388 proj["name"]] if x)389390 lst = Listing(391 source=self.source_id,392 external_id=f"{proj['id']}-{num}",393 url=f"{plans_url}#unite-{num}",394 title=f"{proj['name']} — Unité {num}",395 address=proj["address"],396 sector=proj["sector"],397 city="Gatineau",398 unit_type=unit_type,399 price=None, # complété par DashQ si l'unité y est400 price_label="",401 availability="Disponible",402 area_sqft=area,403 description=desc[:600],404 amenities=list(amenities.get(site, [])),405 images=imgs[: self.max_images + 1],406 details={"Unité": num},407 )408 dq = dashq.get(_unit_key(num))409 if dq:410 self._apply_dashq(lst, dq)411 listings.append(lst)412 except Exception:413 continue414415 uniq: dict[str, Listing] = {}416 for lst in listings:417 uniq.setdefault(lst.external_id, lst)418 return list(uniq.values())419