Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/copley.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/copley.py : connecteur Groupe Copley (groupecopley.com)91# Locations haut de gamme — Westmount, Mont-Royal, Saint-Laurent,92# centre-ville de Montréal, NDG (le site couvre aussi Toronto/Ottawa,93# exclus ici). Webflow CMS rendu serveur : /properties paginé94# (?15d7d54c_page=N), cartes avec champs fs-cmsfilter-*, fiches95# détaillées pour les photos.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import hashlib100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, normalize_unit_type105from .base import BaseConnector106107BASE = "https://www.groupecopley.com"108LIST_URL = f"{BASE}/properties"109110# Dossier d'assets Webflow des photos d'annonces (≠ dossier du thème)111IMG_RE = re.compile(112 r"https://cdn\.prod\.website-files\.com/6449860fc17b160d22960284/"113 r"[^\"\s]+?\.(?:jpg|jpeg|png|webp)", re.I)114115# Quartiers de Montréal qui sont en fait des villes distinctes116_CITY_FROM_NEIGHBOURHOOD = {117 "westmount": "Westmount",118 "mount royal": "Mont-Royal",119 "town of mount royal": "Mont-Royal",120}121122123def _bedrooms_to_type(raw: str) -> str:124 """0 → Studio, 1 → 3½, 2 → 4½, 3 → 5½, 4 → 6½."""125 m = re.search(r"\d+", raw or "")126 if not m:127 return normalize_unit_type(raw)128 n = int(m.group(0))129 return {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}.get(130 n, f"{n} chambres")131132133class CopleyConnector(BaseConnector):134 source_id = "copley"135 request_delay = 0.6136 max_pages = 15 # garde-fou de pagination137 max_details = 60 # garde-fou de fetch des fiches138139 def fetch(self) -> list[Listing]:140 listings: dict[str, Listing] = {}141142 # 1) Pages de la liste (Webflow pagine avec ?15d7d54c_page=N)143 for page_no in range(1, self.max_pages + 1):144 url = LIST_URL if page_no == 1 else f"{LIST_URL}?15d7d54c_page={page_no}"145 try:146 html = self.get(url).text147 except Exception:148 break149 soup = BeautifulSoup(html, "html.parser")150 items = soup.select("div.property_item")151 if not items:152 break153 new = 0154 for it in items:155 try:156 lst = self._parse_card(it)157 except Exception:158 continue159 if lst and lst.external_id not in listings:160 listings[lst.external_id] = lst161 new += 1162 # plus de page suivante annoncée -> stop163 if f"?15d7d54c_page={page_no + 1}" not in html:164 break165 if new == 0 and page_no > 1:166 break167168 # 2) Fiches détaillées (avec cache BD) : photos, description,169 # commodités, disponibilité, chauffage/climatisation/stationnement170 for i, lst in enumerate(listings.values()):171 if i >= self.max_details:172 break173 key = hashlib.sha1("|".join([174 lst.price_label, lst.availability, lst.unit_type,175 str(lst.area_sqft),176 ]).encode("utf-8")).hexdigest()177 try:178 payload = self.detail(lst.external_id, key,179 lambda u=lst.url: self._fetch_detail(u))180 except Exception:181 continue182 if payload.get("images"):183 lst.images = payload["images"]184 if payload.get("description"):185 lst.description = payload["description"]186 if payload.get("amenities"):187 lst.amenities = list(dict.fromkeys(188 lst.amenities + payload["amenities"]))189 if payload.get("availability"):190 lst.availability = payload["availability"]191 if payload.get("details"):192 lst.details = payload["details"]193194 return list(listings.values())195196 # -- fiche détaillée ---------------------------------------------------------197 def _fetch_detail(self, url: str) -> dict:198 detail = self.get(url).text199 payload: dict = {}200 imgs = [u for u in dict.fromkeys(IMG_RE.findall(detail))201 if "-p-" not in u # variantes responsive202 and not re.search(r"logo|icon|favicon|comingsoon", u, re.I)]203 payload["images"] = imgs[:30]204 dsoup = BeautifulSoup(detail, "html.parser")205 rich = dsoup.select_one(".property-header_description, .w-richtext")206 if rich:207 payload["description"] = rich.get_text(" ", strip=True)[:600]208209 # Commodités : liste d'icônes (Laundry, Balcony, Pool, Gym…) +210 # caractéristiques principales (Heating/Cooling/Parking/Backyard)211 amenities = [d.get_text(" ", strip=True)212 for d in dsoup.select(".property-header_features-item")]213 details: dict = {}214 for item in dsoup.select(".main-features_item"):215 lab_el = item.select_one(".text-weight-medium")216 val_el = item.select_one(".text-color-grey50")217 lab = lab_el.get_text(" ", strip=True) if lab_el else ""218 val = val_el.get_text(" ", strip=True) if val_el else ""219 if not lab:220 continue221 amenities.append(f"{lab}: {val}" if val else lab)222 low = lab.lower()223 if low == "cooling" and val and val.lower() not in ("no", "none"):224 details["ac"] = True # « Central Air » etc. (structuré)225 elif low == "parking":226 details["parking"] = {"available": True}227 payload["amenities"] = list(dict.fromkeys(a for a in amenities if a))[:25]228 if details:229 payload["details"] = details230231 # Disponibilité : fil d'Ariane — la variante avec date (« Available232 # Jun 2026 ») est prioritaire sur le simple « Available ».233 bc = dsoup.select_one(".property-header_breadcrumb")234 if bc:235 tags = [t.get_text(" ", strip=True)236 for t in bc.select(".property_availability-tag")]237 tags = [t for t in tags if t]238 dated = next((t for t in tags239 if re.search(r"available\s+\S", t, re.I)), "")240 payload["availability"] = dated or (tags[0] if tags else "")241 return payload242243 # -- parsing d'une carte ---------------------------------------------------244 def _parse_card(self, it) -> Listing | None:245 link = it.select_one("a.property_item-link")246 if not link:247 return None248 href = (link.get("href") or "").split("?")[0]249 m = re.match(r"/properties/([\w\-%.]+)$", href)250 if not m:251 return None252 slug = m.group(1)253254 fields: dict[str, list[str]] = {}255 for f in it.select("[fs-cmsfilter-field]"):256 key = f.get("fs-cmsfilter-field", "")257 fields.setdefault(key, []).append(f.get_text(" ", strip=True))258259 cities = fields.get("city", [])260 raw_city = cities[-1] if cities else ""261 if raw_city.lower() != "montreal":262 return None # Toronto / Ottawa : hors périmètre263 neighbourhood = (fields.get("neighbourhood") or [""])[0]264 ptype = (fields.get("type") or [""])[0]265 if re.search(r"parking|stationnement|commercial|office|storage",266 ptype, re.I):267 return None268 title = (fields.get("title") or [""])[0]269 bedrooms = (fields.get("bedrooms") or [""])[0]270 bathrooms = (fields.get("bathrooms") or [""])[0]271 available = (fields.get("available") or [""])[0].strip().lower()272273 # Superficie : bloc « 1573 sqft » (structuré, sans fs-cmsfilter-field)274 area = None275 for md in it.select(".property_meta-details"):276 t = md.get_text(" ", strip=True)277 m2 = re.match(r"^([\d,]+)\s*sqft$", t, re.I)278 if m2:279 try:280 val = float(m2.group(1).replace(",", ""))281 if 80 <= val <= 20000:282 area = val283 except ValueError:284 pass285 break286287 # Coordonnées embarquées pour le JS de la carte288 lat = lng = None289 lat_el = it.select_one(".data---latitude")290 lng_el = it.select_one(".data---longitude")291 try:292 lat = float(lat_el.get_text(strip=True)) if lat_el else None293 lng = float(lng_el.get_text(strip=True)) if lng_el else None294 except (TypeError, ValueError):295 lat = lng = None296297 price = None298 price_label = ""299 price_el = it.select_one(".property_item-price-text")300 if price_el:301 num = re.sub(r"[^\d.]", "", price_el.get_text(strip=True))302 if num:303 try:304 val = float(num)305 if 100 <= val <= 20000:306 price = val307 price_label = f"${num} / month"308 except ValueError:309 pass310311 city = _CITY_FROM_NEIGHBOURHOOD.get(neighbourhood.lower(), "Montréal")312 sector = "" if city != "Montréal" else neighbourhood313 if sector.lower() == "downtown montreal":314 sector = "Centre-ville"315 elif sector.lower() == "nuns' island":316 sector = "Île-des-Sœurs"317318 img = it.select_one("img.property_image")319 images = [img["src"]] if img and img.get("src") else []320321 # Bandeau de la carte (« Available ») — la fiche précisera la date322 avail_el = it.select_one("a > .text-block")323 availability = (avail_el.get_text(" ", strip=True) if avail_el324 else ("Disponible" if available == "true" else ""))325326 amenities = []327 if bathrooms:328 amenities.append(f"{bathrooms} salle(s) de bain")329330 return Listing(331 source=self.source_id,332 external_id=slug,333 url=f"{BASE}/properties/{slug}",334 title=title or slug.replace("-", " ").title(),335 address=f"{title}, {city}, QC" if title else "",336 sector=sector,337 city=city,338 unit_type=_bedrooms_to_type(bedrooms),339 price=price,340 price_label=price_label,341 availability=availability,342 area_sqft=area,343 amenities=amenities,344 images=images,345 lat=lat,346 lng=lng,347 )348