Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/louis14.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0813# Last Modified : 2026-10-2614#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/louis14.py : connecteur Quartier Louis Quatorze (louis14.ca)91# Condos locatifs (immeubles A-B-C-D, E-F à venir), Lebourgneuf, Québec92# (Groupe Damco). Le site WordPress n'affiche aucun prix : la page /plans/93# embarque le sélecteur de plans Livya (app.livya.com, client « damco »).94# Depuis la refonte Livya du 2026-10-22, le flux RSC de la page plans ne95# contient plus les unités ET le client damco n'a PAS de module inventaire96# SSR (unitSelectorSummaries: []) : les unités ne sont chargées QUE côté97# client (api.realvuu.com, robots.txt interdit — on ne l'appelle pas).98# On rend donc la page plans en navigateur (Scrapfly render_js, patron99# le_fjord) : la grille n'affiche qu'UN immeuble à la fois (boutons de100# navigation data-nav-id) → un rendu par immeuble, js_scenario qui clique101# le bouton voulu puis scrolle les conteneurs internes (grille lazy-loadée),102# et parse des cartes du DOM. external_id = numéro d'unité (« 816-C »),103# identique à l'historique — zéro churn. Adresse/GPS : métadonnées des104# immeubles, toujours présentes dans le RSC de la page.105# ⚠️ Les loyers ne sont PLUS collectables : damco masque les prix sur le106# web (showUnitPriceWeb: false) — l'ancien connecteur les lisait dans le107# JSON brut du RSC, désormais retiré. Aucune surface publique ne les expose.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import html as _html112import json113import re114import time115from urllib.parse import unquote116117from ..schema import Listing, normalize_unit_type118from .base import BaseConnector119120BASE = "https://louis14.ca"121PLANS_PAGE = f"{BASE}/plans/"122LIVYA = "https://app.livya.com"123124# Valeurs observées sur /plans/ — repli si l'extraction dynamique casse125DEFAULT_CLIENT = "damco"126DEFAULT_PROJECT = "louis-14"127DEFAULT_ENTITY = "e5e643c4-89da-4f82-89e5-8895b67c9b3e" # sélecteur de plan128129# conteneur du module Livya sur /plans/ (l'ordre des attributs peut varier)130_CONTAINER_RE = re.compile(131 r'<div[^>]*class="livya-module-container-plans"[^>]*>', re.I)132_ATTR_RE = re.compile(r'data-(project|entity|lang)="([^"]*)"')133_CLIENT_RE = re.compile(r'<script[^>]*data-client="([^"]+)"[^>]*>')134# fragments RSC de Next.js : self.__next_f.push([1,"…"])135_FLIGHT_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')136137# navigation d'immeubles de la grille (bouton actif = aria-current="true")138_NAV_RE = re.compile(139 r'<button data-nav-id="([0-9a-f-]{36})"([^>]*)>([^<]+)</button>')140# cartes d'unités du DOM rendu (même gabarit que le_fjord)141_CARD_RE = re.compile(r'data-unit-id="([0-9a-f-]{36})"')142_NUM_RE = re.compile(r'<h3[^>]*title="([^"]+)"')143_STATUS_RE = re.compile(r'>(Disponible[^<]*|Réservé|Indisponible)<')144_TYPE_RE = re.compile(r'fa-door-open.*?</svg>\s*(?:<span[^>]*>)?([^<]+)', re.S)145_IMG_RE = re.compile(r'url=(https%3A%2F%2F[^&"]+)')146_COUNT_RE = re.compile(r'(\d+)\s*résultats?')147148_MOIS = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5,149 "juin": 6, "juillet": 7, "août": 8, "septembre": 9, "octobre": 10,150 "novembre": 11, "décembre": 12}151_DATE_FR_RE = re.compile(r"(\d{1,2})(?:er)?\s+([a-zûé]+)\s+(\d{4})", re.I)152153# scrolle tous les conteneurs à overflow interne (la grille ne se charge pas154# via le scroll de la fenêtre — auto_scroll Scrapfly inopérant)155_SCROLL_JS = ("document.querySelectorAll('*').forEach(function(e){"156 "if(e.scrollHeight>e.clientHeight+10){e.scrollTop=e.scrollHeight}})")157158159def _chip(card: str, title_re: str) -> str | None:160 """Valeur d'un InfoChip de carte (title=Chambres/Salle de bain/Superficie)."""161 m = re.search(r'title="%s"[^>]*>.*?</svg>\s*(?:<span[^>]*>)?([^<]+)'162 % title_re, card, re.S)163 return _html.unescape(m.group(1)).strip() if m else None164165166def _num(s: str | None) -> float | None:167 digits = re.sub(r"\D", "", s or "")168 return float(digits) if digits else None169170171class Louis14Connector(BaseConnector):172 source_id = "louis14"173 request_delay = 0.7174 max_units = 500 # garde-fou (424 unités au projet)175176 # -- paramètres du module Livya (page /plans/, avec replis) ----------------177 def _module_params(self) -> tuple[str, str, str, str]:178 """(client, project, entity, lang) lus sur /plans/, replis constants."""179 client, project, entity, lang = (DEFAULT_CLIENT, DEFAULT_PROJECT,180 DEFAULT_ENTITY, "fr")181 try:182 page = self.get(PLANS_PAGE).text183 mc = _CLIENT_RE.search(page)184 if mc:185 client = mc.group(1).strip() or client186 md = _CONTAINER_RE.search(page)187 if md:188 attrs = dict(_ATTR_RE.findall(md.group(0)))189 project = attrs.get("project") or project190 entity = attrs.get("entity") or entity191 lang = attrs.get("lang") or lang192 except Exception:193 pass # replis : les constantes observées194 return client, project, entity, lang195196 # -- rendu navigateur --------------------------------------------------------197 def get_rendered(self, url: str, wait_ms: int = 0,198 nav_id: str | None = None) -> str:199 """HTML rendu Scrapfly : clic optionnel sur un bouton d'immeuble200 (data-nav-id) puis scroll des conteneurs internes.201202 Surchargée (même nom que base) pour rester compatible avec le203 record/replay des fixtures — clé de rejeu = URL cible, d'où le204 paramètre « lkb=<nav_id> » ajouté à l'URL par l'appelant pour205 distinguer les rendus des différents immeubles.206 """207 steps: list[dict] = []208 if nav_id:209 steps.append({"execute": {"script": (210 "var b=document.querySelector("211 f"'button[data-nav-id=\"{nav_id}\"]');if(b){{b.click()}}")}})212 steps.append({"wait": 3000})213 for _ in range(8):214 steps.append({"execute": {"script": _SCROLL_JS}})215 steps.append({"wait": 1200})216 html = self.get_scrapfly(url, render_js=True, asp=True,217 rendering_wait=wait_ms or 4000,218 js_scenario=steps)219 if not html:220 raise RuntimeError(f"Scrapfly : rendu vide — {url}")221 return html222223 def fetch(self) -> list[Listing]:224 client, project, entity, lang = self._module_params()225 base_url = (f"{LIVYA}/{lang}/{client}/projects/{project}"226 f"/plans/{entity}?noLayout=1")227228 # 1er rendu : immeuble par défaut + découverte des boutons de229 # navigation et des métadonnées d'immeubles (RSC)230 html = self._render_ok(base_url)231 buildings = self._buildings(html)232 units: dict[str, dict] = {}233 self._collect(html, units)234235 nav = _NAV_RE.findall(html)236 active = {nid for nid, attrs, _ in nav if 'aria-current="true"' in attrs}237 for nid, _attrs, _name in nav:238 if nid in active:239 continue240 html = self._render_ok(f"{base_url}&lkb={nid}", nav_id=nid)241 got = re.search(242 r'data-nav-id="([0-9a-f-]{36})"[^>]*aria-current="true"', html)243 if not got or got.group(1) != nid:244 raise RuntimeError(245 f"app.livya.com (louis14) : le clic sur l'immeuble "246 f"{nid} n'a pas basculé la grille — gabarit changé ?")247 self._collect(html, units)248249 listings: list[Listing] = []250 for u in list(units.values())[: self.max_units]:251 if not (u.get("status") or "").startswith("Disponible"):252 continue253 if not u.get("number"):254 continue # external_id = numéro : requis255 listings.append(self._listing(u, buildings))256 return listings257258 # -- un rendu validé (compteur + cartes complètes), avec retries -------------259 def _render_ok(self, url: str, nav_id: str | None = None) -> str:260 """Rendu dont la grille est complète : le compteur « N résultats »261 doit être présent (sinon gabarit changé) et le nombre de cartes262 uniques doit l'atteindre (grille lazy-loadée) — erreur franche après263 3 tentatives plutôt qu'un rendu tronqué qui dépublierait des unités.264 """265 last_err: Exception | None = None266 for attempt in range(3):267 try:268 html = self.get_rendered(url, wait_ms=4000, nav_id=nav_id)269 except RuntimeError as exc: # rendu vide (hoquet ASP Scrapfly)270 last_err = exc271 if attempt < 2:272 time.sleep(5 * (attempt + 1))273 continue274 m = _COUNT_RE.search(275 _html.unescape(re.sub(r"<[^>]+>", " ", html)))276 if not m:277 last_err = RuntimeError(278 "app.livya.com (louis14) : compteur « N résultats » "279 f"absent du rendu — gabarit Livya changé ? ({url})")280 else:281 announced = int(m.group(1))282 uniques = len(set(_CARD_RE.findall(html)))283 if uniques >= announced:284 return html # announced == 0 : vrai zéro accepté285 last_err = RuntimeError(286 f"app.livya.com (louis14) : {uniques} carte(s) unique(s) "287 f"pour {announced} annoncées — rendu incomplet ? ({url})")288 if attempt < 2:289 time.sleep(5 * (attempt + 1))290 assert last_err is not None291 raise last_err292293 # -- cartes du DOM → unités (fusion champ par champ des occurrences) ---------294 def _collect(self, html: str, units: dict[str, dict]) -> None:295 bmatch = re.search(296 r'data-nav-id="[0-9a-f-]{36}"[^>]*aria-current="true"[^>]*>'297 r'([^<]+)</button>', html)298 bname = _html.unescape(bmatch.group(1)).strip() if bmatch else ""299300 positions = [(x.start(), x.group(1)) for x in _CARD_RE.finditer(html)]301 for idx, (pos, uid) in enumerate(positions):302 end = (positions[idx + 1][0] if idx + 1 < len(positions)303 else pos + 9000)304 card = html[pos:min(end, pos + 9000)]305306 sm = _STATUS_RE.search(card)307 nm = _NUM_RE.search(card)308 tm = _TYPE_RE.search(card)309 im = _IMG_RE.search(card)310 parsed = {311 "status": (_html.unescape(sm.group(1)).strip()312 if sm else None),313 "number": (_html.unescape(nm.group(1)).lstrip("#").strip()314 if nm else None),315 "unit_type": (normalize_unit_type(316 _html.unescape(tm.group(1)).strip()) if tm else None),317 "beds": _num(_chip(card, "Chambres?")),318 "baths": _num(_chip(card, "Salles? de bain")),319 "area": _num(_chip(card, "Superficie")),320 "image": unquote(im.group(1)) if im else None,321 "building": bname or None,322 }323 u = units.setdefault(uid, {})324 for k, v in parsed.items():325 if u.get(k) is None and v is not None:326 u[k] = v327328 # -- métadonnées des immeubles (flux RSC, toujours présentes) ----------------329 @staticmethod330 def _buildings(html: str) -> dict[str, dict]:331 """nom d'immeuble -> {address, city, postalCode, latitude, longitude}."""332 try:333 blob = "".join(334 json.loads(f'"{c}"') for c in _FLIGHT_RE.findall(html))335 except Exception:336 return {}337 dec = json.JSONDecoder()338 out: dict[str, dict] = {}339 for m in re.finditer(r'\{"buildingId"', blob):340 try:341 obj, _ = dec.raw_decode(blob[m.start():m.start() + 8000])342 except Exception:343 continue344 name = (obj.get("name") or "").strip()345 if name and obj.get("address"):346 out.setdefault(name.upper(), obj)347 return out348349 # -- une annonce par unité disponible ----------------------------------------350 def _listing(self, u: dict, buildings: dict[str, dict]) -> Listing:351 num = str(u.get("number") or "").strip()352 bname = (u.get("building") or "").strip()353 b = buildings.get(bname.upper(), {})354355 title = f"Louis 14 — unité {num}"356 if bname:357 title = f"Louis 14 ({bname.title()}) — unité {num}"358359 city = (b.get("city") or "").strip() or "Québec"360 full_addr = ", ".join(x for x in (361 (b.get("address") or "").strip(), city,362 (b.get("postalCode") or "").strip()) if x)363364 # « Disponible » ou « Disponible - 1 mars 2027 » (date française)365 status = (u.get("status") or "").strip()366 availability = "Disponible"367 avail_date = None368 dm = _DATE_FR_RE.search(status)369 if dm and _MOIS.get(dm.group(2).lower()):370 avail_date = (f"{int(dm.group(3)):04d}-"371 f"{_MOIS[dm.group(2).lower()]:02d}-"372 f"{int(dm.group(1)):02d}")373 availability = f"Disponible à partir du {avail_date}"374375 beds, baths = u.get("beds"), u.get("baths")376 area = u.get("area")377 details: dict = {"gestionnaire": BASE}378 if bname:379 details["building"] = bname.title()380381 try:382 lat = float(b["latitude"]) if b.get("latitude") else None383 lng = float(b["longitude"]) if b.get("longitude") else None384 except (TypeError, ValueError):385 lat = lng = None386387 return Listing(388 source=self.source_id,389 external_id=num, # « 816-C » : stable et unique390 url=PLANS_PAGE, # les unités n'ont pas de page propre391 title=title,392 address=full_addr,393 sector="", # quartier non exposé394 city=city,395 unit_type=u.get("unit_type") or "",396 bedrooms=beds if beds and beds > 0 else None,397 bathrooms=baths if baths and baths > 0 else None,398 price=None, # loyers masqués sur le web399 price_label="", # (showUnitPriceWeb: false)400 availability=availability,401 availability_date=avail_date,402 area_sqft=area if area and area > 0 else None,403 description="",404 amenities=[],405 details=details,406 images=[u["image"]] if u.get("image") else [],407 lat=lat,408 lng=lng,409 )410