Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/lynk_olymbec.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/lynk_olymbec.py : connecteur Lynk par Olymbec (lynk.ca)91# Lynk De la Savane — 303 unités au 5200, rue De la Savane, Montréal92# (secteur Namur / De la Savane, CDN-NDG). Site RentCafe derrière un93# challenge Cloudflare (403 pour les robots) : accès direct tenté avec94# en-têtes réalistes, sinon repli sur Scrapfly (rendu JS, ex-Firecrawl).95# Sources combinées (1 annonce par type d'unité — Studio, 3½, 4½, 5½) :96# - /lynk-dls/units : prix marketing « à partir de » par type, inclusions97# « dans mon unité » (icônes) et « aménagements et matériaux » (liste) ;98# - /lynk-dls/floorplans : données RentCafe STRUCTURÉES par plan99# (data-floorplan-size/sqft/price) -> superficie et fourchette de prix100# réelles ; pages de plan (avec cache self.detail) -> unités disponibles101# (« # 923 — Disponible maintenant ») ;102# - /lynk-dls : description du projet + « services et commodités » (icônes)103# + téléphone (lien tel:).104# Le projet Lynk Royale (Trois-Rivières) et Lynk Griffintown105# (« bientôt disponible ») sont exclus.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import re110from urllib.parse import urljoin111112from bs4 import BeautifulSoup113114from ..schema import Listing115from .base import BaseConnector116117BASE = "https://www.lynk.ca"118UNITS_URL = f"{BASE}/lynk-dls/units"119FLOORPLANS_URL = f"{BASE}/lynk-dls/floorplans"120DLS_URL = f"{BASE}/lynk-dls"121122ADDRESS = "5200, rue De la Savane, Montréal, QC H4P 0E2"123SECTOR = "Namur / De la Savane (CDN-NDG)"124125# « Studio à partir de 1 380 $ par mois », « 3 ½ à partir de 1 700 $ … »126TYPE_PRICE_RE = re.compile(127 r"(Studio|\d\s*½|\d\s*1/2)\s*à partir de\s*([\d\s ,]+)\s*\$",128 re.I)129130IMG_RE = re.compile(131 r"https://resource\.rentcafe\.com/image/upload/[^\"'\s\\]+?\.(?:jpg|jpeg)",132 re.I)133134# nombre de chambres (data-floorplan-size / nom du plan) -> type Lou-Ka135BEDROOMS_TO_TYPE = {0: "Studio", 1: "3½", 2: "4½", 3: "5½"}136137BROWSER_HEADERS = {138 "Accept": ("text/html,application/xhtml+xml,application/xml;q=0.9,"139 "image/avif,image/webp,*/*;q=0.8"),140 "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8",141 "Sec-Fetch-Dest": "document",142 "Sec-Fetch-Mode": "navigate",143 "Sec-Fetch-Site": "none",144 "Upgrade-Insecure-Requests": "1",145}146147148def _strip_tags(html: str) -> str:149 txt = re.sub(r"<script.*?</script>|<style.*?</style>|<svg.*?</svg>", " ",150 html, flags=re.S | re.I)151 txt = re.sub(r"<[^>]+>", " ", txt)152 return re.sub(r"\s+", " ", txt)153154155def _fmt_price(raw: str) -> str:156 """« 1650 » -> « 1 650 $ » (affichage de la fourchette RentCafe)."""157 try:158 n = int(float(raw))159 except (TypeError, ValueError):160 return ""161 return f"{n:,}".replace(",", " ") + " $"162163164class LynkOlymbecConnector(BaseConnector):165 source_id = "lynk_olymbec"166 request_delay = 0.8167 max_details = 10 # plafond de VRAIES requêtes de pages plan par synchro168169 def __init__(self) -> None:170 super().__init__()171 self._detail_fetches = 0172173 def _get_page(self, url: str) -> str:174 """Essaie l'accès direct (en-têtes navigateur), sinon le rendu175 Scrapfly (get_rendered, avec retry), sinon un dernier appel Scrapfly176 ASP direct en dernier rideau."""177 try:178 resp = self.get(url, headers=BROWSER_HEADERS)179 if "Just a moment" not in resp.text:180 return resp.text181 except Exception:182 pass183 try:184 html = self.get_rendered(url) # Cloudflare -> rendu Scrapfly185 if html and "Just a moment" not in html:186 return html187 except Exception:188 pass189 return self.get_scrapfly(url)190191 # -- sections d'icônes (ysi-icon-widget : libellé + sous-titre) -----------192 @staticmethod193 def _icon_labels(html: str) -> list[str]:194 out: list[str] = []195 soup = BeautifulSoup(html, "html.parser")196 for w in soup.select(".ysi-icon-widget"):197 lines = [t for t in w.stripped_strings]198 if not lines:199 continue200 label = lines[0].strip()201 caption = " ".join(lines[1:]).strip()202 if caption and len(caption) <= 90:203 out.append(f"{label} — {caption}")204 elif label:205 out.append(label)206 return out207208 # -- page d'un plan RentCafe : unités disponibles --------------------------209 def _fetch_plan(self, url: str) -> dict:210 if self._detail_fetches >= self.max_details:211 raise RuntimeError("plafond de requêtes de plans atteint")212 self._detail_fetches += 1213 html = self._get_page(url)214 text = _strip_tags(html)215 units = []216 # « Appartement : # 923 Disponible maintenant Appelez pour connaître… »217 for m in re.finditer(r"Appartement\s*:\s*#\s*(\d+)\s+(.*?)\s*"218 r"(?:Appelez|Contactez|\d[\d\s]*\$)", text):219 dispo = m.group(2).strip()220 if len(dispo) > 60:221 dispo = ""222 units.append({"no": m.group(1), "dispo": dispo})223 images = [u for u in dict.fromkeys(IMG_RE.findall(html))224 if not re.search(r"logo|icon|chevron|download|lockup", u, re.I)]225 return {"units": units, "images": images[:5]}226227 def fetch(self) -> list[Listing]:228 # un échec transitoire doit être journalisé comme ÉCHEC par ingest229 # (ok=0), pas comme un passage « ok » à 0 annonce qui marque tout230 # le parc manquant — on laisse donc l'exception remonter231 listings: list[Listing] = []232 units_html = self._get_page(UNITS_URL)233 if not units_html:234 raise RuntimeError(235 "page /units inaccessible (direct, rendu Scrapfly et ASP)")236 units_text = _strip_tags(units_html)237 units_soup = BeautifulSoup(units_html, "html.parser")238239 # prix marketing « à partir de » par type (Studio, 3½, 4½, 5½)240 marketing: dict[str, str] = {}241 for m in TYPE_PRICE_RE.finditer(units_text):242 raw_type, raw_price = m.group(1), m.group(2)243 unit_type = ("Studio" if raw_type.lower().startswith("studio")244 else re.sub(r"\s*(?:½|1/2)", "½",245 raw_type.replace(" ", "")))246 num = re.sub(r"[^\d]", "", raw_price)247 if num and unit_type not in marketing:248 marketing[unit_type] = num249250 # commodités de l'unité : icônes « dans mon unité » + liste251 # « aménagements et matériaux exceptionnels »252 unit_amen = self._icon_labels(units_html)253 for li in units_soup.select("ul.pl-3 li"):254 t = li.get_text(" ", strip=True)255 if t:256 unit_amen.append(t)257258 # Photos des unités/immeuble (jpg de la galerie RentCafe)259 images = [u for u in dict.fromkeys(IMG_RE.findall(units_html))260 if not re.search(r"logo|icon|chevron|download|lockup",261 u, re.I)][:25]262263 # page projet : description, services de l'immeuble, téléphone264 desc = ("Lynk De la Savane (Olymbec) — 303 unités locatives "265 "intelligentes, studio à 5½, au 5200 De la Savane à Montréal.")266 building_amen: list[str] = []267 phone = ""268 try:269 dls_html = self._get_page(DLS_URL)270 m = re.search(r"<p[^>]*>([^<]{80,400})</p>", dls_html)271 if m:272 desc = re.sub(r"\s+", " ", m.group(1)).strip()[:600]273 building_amen = self._icon_labels(dls_html)274 mt = re.search(r'href="tel:[^"]*?(\d{3})[\s.\-]?(\d{3})[\s.\-]?(\d{4})"',275 dls_html)276 if mt:277 phone = "-".join(mt.groups())278 except Exception:279 pass280281 # plans RentCafe : superficie + fourchette de prix STRUCTURÉES282 # (data-floorplan-*) et unités disponibles (pages plan, avec cache)283 plans: dict[str, dict] = {} # type -> données agrégées284 try:285 fp_html = self._get_page(FLOORPLANS_URL)286 seen_slugs: set[str] = set()287 for a in BeautifulSoup(fp_html, "html.parser").select(288 "a[data-floorplan-name]"):289 # seules les ancres pointant vers une page de plan portent les290 # attributs sqft/price ; chaque plan apparaît 2x (desktop+mobile)291 href = urljoin(BASE, a.get("href", ""))292 if "/floorplans/" not in href or "#" in href:293 continue294 slug = href.rstrip("/").rsplit("/", 1)[-1]295 if slug in seen_slugs:296 continue297 seen_slugs.add(slug)298299 name = a.get("data-floorplan-name", "")300 mb = re.match(r"(\d)\s*Bedroom", name, re.I)301 beds = (0 if name.strip().lower() == "studio"302 else int(mb.group(1)) if mb else None)303 unit_type = BEDROOMS_TO_TYPE.get(beds) if beds is not None else None304 if not unit_type:305 continue306 agg = plans.setdefault(unit_type, {307 "sqft": [], "price": [], "units": [], "images": []})308 # superficie « 657 -829 » et prix « 1650 -2293.2 » (attributs)309 for v in re.findall(r"\d+(?:\.\d+)?",310 a.get("data-floorplan-sqft", "") or ""):311 agg["sqft"].append(float(v))312 for v in re.findall(r"\d+(?:\.\d+)?",313 a.get("data-floorplan-price", "") or ""):314 agg["price"].append(float(v))315 # page du plan -> unités disponibles (cache : clé = attributs)316 key = "v1:" + "|".join([317 name, a.get("data-floorplan-sqft", "") or "",318 a.get("data-floorplan-price", "") or ""])319 try:320 payload = self.detail(f"fp-{slug}", key,321 lambda u=href: self._fetch_plan(u))322 except Exception:323 payload = {}324 agg["units"] += payload.get("units", [])325 agg["images"] += [u for u in payload.get("images", [])326 if u not in agg["images"]]327 except Exception:328 pass329330 # 1 annonce par type (ordre stable), union marketing + plans RentCafe331 for unit_type in ("Studio", "3½", "4½", "5½"):332 mk_num = marketing.get(unit_type)333 plan = plans.get(unit_type)334 if not mk_num and not plan:335 continue336337 price = None338 price_label = ""339 if plan and plan["price"]:340 lo, hi = min(plan["price"]), max(plan["price"])341 if 100 <= lo <= 20000:342 price = lo343 price_label = (f"de {_fmt_price(lo)} à {_fmt_price(hi)} par mois"344 if hi > lo else f"{_fmt_price(lo)} par mois")345 elif mk_num:346 val = float(mk_num)347 if 100 <= val <= 20000:348 price = val349 price_label = f"à partir de {mk_num} $ par mois"350351 area = None352 amenities = list(unit_amen)353 if plan and plan["sqft"]:354 lo_s, hi_s = min(plan["sqft"]), max(plan["sqft"])355 if 80 <= lo_s <= 20000:356 area = lo_s357 amenities.append(358 f"Superficie : {int(lo_s)} à {int(hi_s)} pi²"359 if hi_s > lo_s else f"Superficie : {int(lo_s)} pi²")360 amenities += [a for a in building_amen if a not in amenities]361362 availability = ""363 desc_extra = ""364 if plan and plan["units"]:365 dispos = [u["dispo"] for u in plan["units"] if u["dispo"]]366 availability = dispos[0] if dispos else ""367 nos = ", ".join("#" + u["no"] for u in plan["units"][:12])368 desc_extra = (f" — {len(plan['units'])} unité(s) disponible(s)"369 f" : {nos}")370371 details: dict = {}372 if phone:373 details["contact"] = {"phone": phone}374375 ext = f"dls-{unit_type.replace('½', '.5').lower()}"376 listings.append(Listing(377 source=self.source_id,378 external_id=ext,379 url=UNITS_URL,380 title=f"Lynk De la Savane — {unit_type}",381 address=ADDRESS,382 sector=SECTOR,383 city="Montréal",384 unit_type=unit_type,385 price=price,386 price_label=price_label,387 availability=availability,388 area_sqft=area,389 description=(desc + desc_extra)[:700],390 amenities=list(dict.fromkeys(amenities))[:40],391 details=details,392 images=(plan["images"] if plan else []) + images,393 ))394 return listings395