Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/devimco.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-09-1414#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/devimco.py : connecteur Devimco Appartements91# (devimco.com/appartements — St Ann & Hexagone à Griffintown, Alexander &92# Maestria au centre-ville de Montréal, Éolia / Luméo / Nobel à Brossard,93# Ostral à Longueuil).94# Chaque page projet embarque un iframe Planpoint (app.planpoint.io) ;95# l'inventaire complet s'obtient via l'API JSON de Planpoint :96# POST https://app.planpoint.io/api/projects/find {namespace, hostName}97# -> floors[] -> units[] (prix, chambres, photos, disponibilité...).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import html as htmllib102import re103import time104import urllib.parse105106from ..schema import Listing, normalize_unit_type107from .base import BaseConnector108109BASE = "https://devimco.com"110HUB_URL = f"{BASE}/appartements"111PLANPOINT_FIND = "https://app.planpoint.io/api/projects/find"112PLANPOINT_GROUP_FIND = "https://app.planpoint.io/api/groups/find"113114PROJECT_RE = re.compile(115 r"https://devimco\.com/appartements/a-louer/"116 r"(montreal|rive-sud-de-montreal)/([a-z\-]+)/([a-z0-9\-]+)")117118# secteur d'URL -> (ville, secteur affiché)119SECTORS = {120 "centre-ville": ("Montréal", "Centre-ville"),121 "griffintown": ("Montréal", "Griffintown"),122 "brossard": ("Brossard", "Quartier DIX30"),123 "longueuil": ("Longueuil", "Vieux-Longueuil"),124}125126127def _unit_type(bedrooms: str) -> str:128 s = (bedrooms or "").lower()129 if "studio" in s:130 return "Studio"131 m = re.search(r"(\d+)", s)132 if not m:133 return bedrooms or ""134 n = int(m.group(1))135 return "Studio" if n == 0 else f"{n + 2}½"136137138# Jetons de la liste `inclusions` de l'API Planpoint -> details canoniques.139# Champ structuré côté source (liste séparée par des virgules), donc mappé140# explicitement ; un jeton absent = inconnu (jamais False).141_INCLUSION_TOKENS = {142 "heating": ("inclusions", "heating"),143 "electricity": ("inclusions", "electricity"),144 "hot water": ("inclusions", "hot_water"),145 "internet": ("inclusions", "internet"),146 "cable": ("inclusions", "cable"),147 "stove": ("appliances", "stove"),148 "refrigerator": ("appliances", "fridge"),149 "fridge": ("appliances", "fridge"),150 "dishwasher": ("appliances", "dishwasher"),151 "air conditioning": (None, "ac"),152 "balcony": (None, "balcony"),153}154155156def _details_from_inclusions(tokens: list[str]) -> dict:157 """« internet, electricity, heating, stove, refrigerator… » -> details."""158 details: dict = {}159 lows = [t.lower() for t in tokens]160 for tok in lows:161 for key, (group, name) in _INCLUSION_TOKENS.items():162 if key in tok:163 if group:164 details.setdefault(group, {})[name] = True165 else:166 details[name] = True167 if "washer" in " ".join(lows) and "dryer" in " ".join(lows):168 details.setdefault("appliances", {})["washer_dryer"] = True169 return details170171172class DevimcoConnector(BaseConnector):173 source_id = "devimco"174 request_delay = 0.6175 max_projects = 15 # garde-fou176177 def _get_html(self, url: str) -> str:178 """HTML de `url`, tolérant au pare-feu Sucuri CloudProxy.179180 Vu 2026-09-13 : devimco.com est passé derrière Sucuri/Cloudproxy,181 qui répond par intermittence 307 + challenge JavaScript (cookie182 sucuri_cloudproxy) aux clients sans navigateur — un statut < 400183 invisible de raise_for_status(), dont la soupe sans lien projet184 devenait un « 0 trouvé ok » silencieux. Direct d'abord (gratuit si185 Sucuri laisse passer), sinon escalade Scrapfly ASP + rendu JS qui186 passe le challenge (pattern brio, fix 195f19a).187 """188 try:189 resp = self.get(url)190 if (resp.status_code != 307191 and "sucuri_cloudproxy" not in resp.text):192 return resp.text193 except Exception: # noqa: BLE001 — direct bloqué : on escalade194 pass195 return self.get_rendered(url)196197 def fetch(self) -> list[Listing]:198 listings: list[Listing] = []199 hub = self._get_html(HUB_URL)200201 # 1) Pages projets (a-louer/<région>/<secteur>/<projet>)202 projects: dict[str, tuple[str, str]] = {}203 for m in PROJECT_RE.finditer(hub):204 url = m.group(0)205 sector_slug, proj_slug = m.group(2), m.group(3)206 # ignorer les pages de secteur (sans slug projet "…-appartements")207 if proj_slug.endswith("-appartements"):208 projects[url] = (sector_slug, proj_slug)209 if not projects:210 raise RuntimeError(211 "devimco : aucun lien projet dans le hub — challenge Sucuri "212 f"non passé ou site remanié ? — {HUB_URL}")213214 for i, (proj_url, (sector_slug, proj_slug)) in \215 enumerate(projects.items()):216 if i >= self.max_projects:217 break218 try:219 listings.extend(220 self._fetch_project(proj_url, sector_slug))221 except Exception:222 continue223 return listings224225 # -- un projet ---------------------------------------------------------------226 def _fetch_project(self, proj_url: str, sector_slug: str) -> list[Listing]:227 out: list[Listing] = []228 html = self._get_html(proj_url)229230 # iframe Planpoint : soit un projet (/<ns>/<host>), soit un groupe231 # de phases. Depuis 2026-08, le widget groupe est /g/<x>/<ns> (deux232 # segments, le namespace de l'API est le DERNIER) ; l'ancien format233 # /g/<ns> reste possible -> on essaie les deux segments.234 projects: list[dict] = []235 m = re.search(236 r"https://app\.planpoint\.io/g/([A-Za-z0-9\-]+)"237 r"(?:/([A-Za-z0-9\-]+))?", html)238 if m:239 for ns in filter(None, (m.group(2), m.group(1))):240 try:241 group = self._planpoint(PLANPOINT_GROUP_FIND,242 {"namespace": ns.lower()})243 except Exception:244 continue245 projects = group.get("projects") or []246 if projects:247 break248 else:249 # namespace parfois avec espace encodé (ex. groupe%20devimco)250 m = re.search(251 r"https://app\.planpoint\.io/([a-z0-9\-]+(?:%20[a-z0-9\-]+)*)"252 r"/([a-z0-9\-]+)\?",253 html)254 if not m:255 return out256 projects = [self._planpoint(257 PLANPOINT_FIND,258 {"namespace": urllib.parse.unquote(m.group(1)),259 "hostName": m.group(2)})]260261 # Adresse affichée sur la page Devimco (lien Google Maps) : repli262 # pour les phases dont l'API Planpoint n'a pas d'adresse263 # (ex. Maestria Tour B, Hexagone 2).264 page_address = ""265 m = re.search(r"google\.[a-z.]+/maps/search/\?[^\"']*query=([^\"'&]+)",266 html)267 if m:268 page_address = htmllib.unescape(269 urllib.parse.unquote(m.group(1))).strip()270271 city, sector = SECTORS.get(sector_slug, ("Montréal", sector_slug))272 for project in projects:273 try:274 out.extend(self._parse_units(project, proj_url, city, sector,275 page_address))276 except Exception:277 continue278 return out279280 def _planpoint(self, endpoint: str, payload: dict) -> dict:281 wait = self.request_delay - (time.time() - self._last_request)282 if wait > 0:283 time.sleep(wait)284 resp = self.session.post(endpoint, json=payload, timeout=60)285 self._last_request = time.time()286 resp.raise_for_status()287 return resp.json() or {}288289 def _parse_units(self, project: dict, proj_url: str,290 city: str, sector: str,291 page_address: str = "") -> list[Listing]:292 out: list[Listing] = []293 namespace = project.get("namespace") or ""294 name = project.get("name") or namespace295 address = (project.get("address") or "").split(", Quebec")[0]296 if not address:297 address = page_address298 lat, lng = project.get("lat"), project.get("lng") or project.get("lon")299 for floor in project.get("floors") or []:300 floor_name = floor.get("name") or ""301 for u in floor.get("units") or []:302 try:303 if (u.get("availability") or "").lower() != "available":304 continue # loué / réservé / à venir305 price = u.get("price")306 if u.get("unitPriceTBD") or not price:307 continue # pas de prix affiché308 unit_name = str(u.get("name") or "")309 images = [img for img in310 (u.get("images") or []) +311 (u.get("layoutGallery") or [])312 if isinstance(img, str) and img.startswith("http")]313 inclusions = [s.strip() for s in314 (u.get("inclusions") or "").split(",")315 if s.strip()]316 sqft = u.get("squareFeet")317 amenities = list(inclusions)318 if sqft:319 amenities.append(f"{sqft} pi²")320 if u.get("bathrooms"):321 amenities.append(f"{u['bathrooms']} salle(s) de bain")322 if u.get("furnished"):323 amenities.append("Meublé")324 availability = "Disponible"325 if u.get("deliveryDate"):326 availability = f"Disponible : {u['deliveryDate']}"327328 # Superficie structurée de l'API (sinon None)329 area = None330 try:331 if sqft and 80 <= float(sqft) <= 20000:332 area = float(sqft)333 except (TypeError, ValueError):334 pass335336 # Meublé : booléen explicite de l'API337 furnished = (bool(u["furnished"])338 if isinstance(u.get("furnished"), bool)339 else None)340341 # Type exact « 3.5 » de l'API, sinon via nb de chambres342 unit_type = (normalize_unit_type(str(u.get("type") or ""))343 or _unit_type(u.get("bedrooms") or ""))344345 out.append(Listing(346 source=self.source_id,347 external_id=u.get("_id") or f"{namespace}-{unit_name}",348 url=proj_url,349 title=f"{name} — unité {unit_name}",350 address=address,351 sector=sector,352 city=city,353 unit_type=unit_type,354 price=float(price)355 if 100 <= float(price) <= 20000 else None,356 price_label=f"{int(price)} $/mois",357 availability=availability,358 area_sqft=area,359 furnished=furnished,360 description=(f"Étage {floor_name} — "361 f"{u.get('orientation') or ''}").strip(" —"),362 amenities=list(dict.fromkeys(amenities)),363 details=_details_from_inclusions(inclusions),364 images=list(dict.fromkeys(images)),365 lat=float(lat) if lat else None,366 lng=float(lng) if lng else None,367 ))368 except Exception:369 continue370 return out371