Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/progim.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0814#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/progim.py : connecteur Gestion Immobilière Progim91# (progimannonces.bstk.io — plateforme Building Stack, Grand Montréal :92# Montréal, Dorval, Longueuil, Sainte-Julie, Châteauguay, Charlemagne...)93# La page /Listing/Listings embarque `var units = [...]` (JSON complet des94# unités). Le détail d'une unité (photos, équipements, description) vient95# de POST /Listing/ApartmentView avec `id=<ApartmentId>`.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import hashlib100import json101import re102import time103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type, strip_accents107from .base import BaseConnector108109BASE = "https://progimannonces.bstk.io"110LIST_URL = f"{BASE}/Listing/Listings"111VIEW_URL = f"{BASE}/Listing/ApartmentView"112113# Villes de la Communauté métropolitaine de Montréal (Grand Montréal)114# desservies par Progim. Tout le reste (ex. Bromont, Saint-Césaire) est exclu.115GRAND_MTL = {116 "montreal", "laval", "longueuil", "dorval", "sainte-julie", "charlemagne",117 "chateauguay", "brossard", "boucherville", "repentigny", "terrebonne",118 "saint-lambert", "pointe-claire", "kirkland", "beaconsfield", "lachine",119 "verdun", "lasalle", "mont-royal", "westmount", "cote-saint-luc",120 "dollard-des-ormeaux", "pierrefonds", "anjou", "saint-leonard",121 "montreal-nord", "montreal-est", "saint-laurent", "candiac", "la prairie",122 "chambly", "varennes", "sainte-catherine", "delson", "saint-constant",123 "mascouche", "blainville", "mirabel", "saint-eustache", "deux-montagnes",124 "rosemere", "boisbriand", "sainte-therese", "vaudreuil-dorion",125 "l'ile-perrot", "pincourt", "beauharnois", "mercier", "saint-bruno",126 "saint-basile-le-grand", "mcmasterville", "beloeil", "otterburn park",127 "mont-saint-hilaire", "carignan", "richelieu", "l'assomption",128 "saint-sulpice",129}130131132def _in_grand_mtl(city: str) -> bool:133 key = strip_accents((city or "").strip().lower())134 return any(key == c or key.startswith(c + "-") for c in GRAND_MTL)135136137_CITY_CANON = {"montreal": "Montréal", "chateauguay": "Châteauguay",138 "levis": "Lévis", "quebec": "Québec"}139140141def _canon_city(city: str) -> str:142 """Uniformise la graphie ('Montreal' -> 'Montréal')."""143 return _CITY_CANON.get(strip_accents(city.strip().lower()), city.strip())144145146# Clés structurées des fragments ApartmentView (attributs `label for=`)147# de la plateforme Building Stack -> champs canoniques Lou-Ka.148_EQUIP_INCLUSIONS = {149 "HeatingIncluded": "heating",150 "HotWaterIncluded": "hot_water",151 "ElectricityIncluded": "electricity",152 "InternetIncluded": "internet",153 "CableIncluded": "cable",154}155_EQUIP_APPLIANCES = {156 "Fridge": "fridge",157 "Stove": "stove",158 "Dishwasher": "dishwasher",159 "DishWasher": "dishwasher",160 "Washer": "washer_dryer",161 "Dryer": "washer_dryer",162}163def _unit_type_from_bedrooms(bedrooms, unit_name: str = "") -> str:164 """Building Stack donne le nb de chambres ; 0 ch -> Studio, n ch -> (n+2)½."""165 try:166 n = int(bedrooms)167 except (TypeError, ValueError):168 return normalize_unit_type(unit_name)169 if n <= 0:170 return "Studio"171 return f"{n + 2}½"172173174class ProgimConnector(BaseConnector):175 source_id = "progim"176 request_delay = 0.5177 max_details = 120 # garde-fou (une requête ApartmentView par unité)178179 def fetch(self) -> list[Listing]:180 listings: list[Listing] = []181 try:182 html = self.get(LIST_URL).text183 except Exception:184 return listings185186 m = re.search(r"var units = (\[.*?\]);", html, re.S)187 if not m:188 return listings189 try:190 units = json.loads(m.group(1))191 except ValueError:192 return listings193194 blobs: dict[str, dict] = {} # external_id -> unité JSON brute195 for u in units:196 try:197 apt = u.get("Apartment") or {}198 addr = u.get("Address") or {}199 city = (addr.get("City") or u.get("City") or "").strip()200 if not _in_grand_mtl(city):201 continue # hors Grand Montréal (ex. Bromont)202 if not apt.get("IsResidential", True):203 continue # commercial / stationnement204 ext_id = str(apt.get("ApartmentId") or u.get("ApartmentId") or "")205 if not ext_id:206 continue207 price = apt.get("Price")208 price_label = apt.get("PriceFormatted") or ""209 address = addr.get("AddressLine1") or ""210 building = u.get("BuildingName") or address211 unit_name = apt.get("UnitName") or ""212 # placeholders relatifs (/Content/…/residential.svg) exclus213 images = [img for img in214 (u.get("PreviewUrl"), u.get("BuildingPreviewUrl"))215 if img and img.startswith("http")]216 building_url = u.get("BuildingUrl") or ""217 url = BASE + building_url if building_url.startswith("/") \218 else (building_url or LIST_URL)219 lat = lng = None220 try:221 lat = float(addr.get("Latitude"))222 lng = float(addr.get("Longitude"))223 except (TypeError, ValueError):224 pass225226 # Superficie : champ structuré `Apartment.Area` (pi²)227 area = apt.get("Area")228 area_sqft = float(area) if isinstance(area, (int, float)) \229 and 80 <= area <= 20000 else None230231 # Salles de bains (structuré) -> commodité d'affichage232 amenities: list[str] = []233 nb_bath = apt.get("NumberOfBathrooms")234 if isinstance(nb_bath, (int, float)) and nb_bath > 0:235 n = int(nb_bath)236 amenities.append(f"{n} salles de bains" if n > 1237 else "1 salle de bain")238239 # Détails structurés : stationnement/rangement (booléens de la240 # plateforme) + contact de location (nom, téléphone, courriel)241 details: dict = {}242 if isinstance(u.get("ParkingsIsAvailable"), bool):243 details["parking"] = {"available": u["ParkingsIsAvailable"]}244 if isinstance(u.get("StoragesIsAvailable"), bool):245 details["storage"] = u["StoragesIsAvailable"]246 contact: dict = {}247 contacts = (u.get("Building") or {}).get(248 "ListingEmployeesContacts") or []249 if contacts:250 c = contacts[0]251 phone = c.get("FormattedPhoneNumber") or c.get("PhoneNumber")252 if phone:253 digits = re.sub(r"\D", "", phone)[-10:]254 if len(digits) == 10:255 contact["phone"] = (f"{digits[:3]}-{digits[3:6]}"256 f"-{digits[6:]}")257 if c.get("Email"):258 contact["email"] = c["Email"]259 elif (u.get("Building") or {}).get("Phone"):260 digits = re.sub(r"\D", "", u["Building"]["Phone"])[-10:]261 if len(digits) == 10:262 contact["phone"] = (f"{digits[:3]}-{digits[3:6]}"263 f"-{digits[6:]}")264 if contact:265 details["contact"] = contact266267 blobs[ext_id] = u268 listings.append(Listing(269 source=self.source_id,270 external_id=ext_id,271 url=url,272 title=f"{building} — unité {unit_name}" if unit_name273 else building,274 address=address,275 sector="",276 city=_canon_city(city),277 unit_type=_unit_type_from_bedrooms(278 apt.get("NumberOfBedrooms"), unit_name),279 price=float(price) if isinstance(price, (int, float))280 and 100 <= price <= 20000 else None,281 price_label=price_label,282 availability="",283 area_sqft=area_sqft,284 amenities=amenities,285 details=details,286 images=images,287 lat=lat,288 lng=lng,289 ))290 except Exception:291 continue292293 # Détail de chaque unité (fragment ApartmentView via cache self.detail :294 # un vrai POST seulement si l'unité JSON de la liste a changé)295 budget = {"n": 0}296 for lst in listings:297 key = hashlib.sha1(json.dumps(298 blobs.get(lst.external_id, {}), sort_keys=True,299 ensure_ascii=False).encode()).hexdigest()300301 def _fetch(ext_id=lst.external_id):302 if budget["n"] >= self.max_details:303 raise RuntimeError("plafond de fiches atteint")304 budget["n"] += 1305 return self._fetch_view(ext_id)306307 try:308 payload = self.detail(lst.external_id, key, _fetch)309 except Exception:310 payload = {}311 self._apply_view(lst, payload)312313 return listings314315 # -- détail (fragment HTML ApartmentView) ---------------------------------316 def _fetch_view(self, ext_id: str) -> dict:317 """POST /Listing/ApartmentView (throttlé) -> payload structuré."""318 wait = self.request_delay - (time.time() - self._last_request)319 if wait > 0:320 time.sleep(wait)321 resp = self.session.post(VIEW_URL, data={"id": ext_id},322 timeout=self.timeout)323 self._last_request = time.time()324 resp.raise_for_status()325 return self._parse_view(resp.text)326327 @staticmethod328 def _parse_view(frag: str) -> dict:329 payload: dict = {}330 soup = BeautifulSoup(frag, "html.parser")331332 # Photos de l'unité333 imgs = re.findall(334 r'https://wfiles\.buildingstack\.com/resources/image/[A-Za-z0-9]+'335 r'(?:/[a-z]+)?', frag)336 if imgs:337 payload["images"] = list(dict.fromkeys(imgs))338339 # Disponibilité : la plateforme n'affiche que des unités disponibles ;340 # le fragment précise parfois une date ("Disponible dès maintenant!").341 avail = soup.find(string=re.compile(342 r"^\s*Disponible (dès|le|à partir|maintenant|immédiatement)", re.I))343 if avail:344 payload["availability"] = avail.strip()345346 # Général : paires titre/valeur (superficie, étage, chambres, sdb)347 general: dict[str, str] = {}348 for li in soup.select("ul.main-items li"):349 t = li.select_one("p.title")350 v = li.select_one("h4")351 if t and v:352 k = strip_accents(t.get_text(" ", strip=True).lower())353 general.setdefault(k, v.get_text(" ", strip=True))354 m = re.match(r"(\d[\d\s]*(?:[.,]\d+)?)",355 general.get("superficie (pi.ca)", ""))356 if m:357 try:358 area = float(m.group(1).replace(" ", "").replace(",", "."))359 if 80 <= area <= 20000:360 payload["area_sqft"] = area361 except ValueError:362 pass363 if general.get("etage", "").isdigit():364 floor = int(general["etage"])365 if 0 < floor <= 60:366 payload["floor"] = floor367368 # Équipements booléens : `label for=<Clé>` + valeur Oui/Non (clés369 # structurées Building Stack : HeatingIncluded, Furnished, Fridge…)370 inclusions: dict[str, bool] = {}371 appliances: dict[str, bool] = {}372 amenities: list[str] = []373 for li in soup.select("ul.main-items.amentities li"):374 lab = li.find("label")375 v = li.select_one("h4")376 if not lab or not v:377 continue378 key = lab.get("for") or ""379 val = v.get_text(strip=True).strip().lower()380 flag = val in ("oui", "yes")381 if key in _EQUIP_INCLUSIONS:382 inclusions[_EQUIP_INCLUSIONS[key]] = flag383 elif key == "Furnished":384 payload["furnished"] = flag385 if flag:386 amenities.append(lab.get_text(" ", strip=True))387 for lab in soup.select("ul.amentity-links label"):388 key = lab.get("for") or ""389 if key in _EQUIP_APPLIANCES:390 appliances[_EQUIP_APPLIANCES[key]] = True391 txt = lab.get_text(" ", strip=True)392 if txt and txt not in amenities:393 amenities.append(txt)394 if inclusions:395 payload["inclusions"] = inclusions396 if appliances:397 payload["appliances"] = appliances398 if amenities:399 payload["amenities"] = amenities400401 # Description (section Commentaires)402 notes = soup.select_one("div.unit-notes")403 if notes:404 desc = re.sub(r"\s+", " ", notes.get_text(" ", strip=True))405 desc = re.sub(r"^Commentaires\s*", "", desc).strip(" •")406 if desc:407 payload["description"] = desc[:600]408409 return payload410411 @staticmethod412 def _apply_view(lst: Listing, payload: dict) -> None:413 """Applique le payload (frais ou en cache) sur l'annonce."""414 if payload.get("images"):415 lst.images = list(dict.fromkeys(lst.images + payload["images"]))416 lst.availability = payload.get("availability", "Disponible")417 if lst.area_sqft is None and payload.get("area_sqft") is not None:418 lst.area_sqft = payload["area_sqft"]419 if payload.get("floor") is not None:420 lst.details["floor"] = payload["floor"]421 if payload.get("furnished") is not None:422 lst.furnished = payload["furnished"]423 if payload.get("inclusions"):424 lst.details["inclusions"] = {**payload["inclusions"],425 **lst.details.get("inclusions", {})}426 if payload.get("appliances"):427 lst.details["appliances"] = {**payload["appliances"],428 **lst.details.get("appliances", {})}429 for a in payload.get("amenities") or []:430 if a not in lst.amenities:431 lst.amenities.append(a)432 if payload.get("description"):433 lst.description = payload["description"]434