Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/trudel.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-10-2214#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/trudel.py : connecteur Trudel — Fleur de Lys condos locatifs91# (le21mars.ca — 550, boul. Wilfrid-Hamel, Québec, secteur Vanier).92# Inventaire servi par Livya (ex-RealVuu), client « trudel », projet « fdl ».93# Depuis la refonte Livya du 2026-10-22, le flux RSC de la page plans ne94# contient plus les unités ET le client trudel n'a PAS de module inventaire95# SSR (unitSelectorSummaries: []) : les unités ne sont chargées QUE côté96# client (api.realvuu.com, robots.txt interdit — on ne l'appelle pas).97# On rend donc la page plans en navigateur (Scrapfly render_js, patron98# quartier_sila/somex) : le DOM rendu contient une vue TABLEAU complète99# (colonnes Nom/Étage/Chambres/Salles de bain/Superficie/Prix/Statut — les100# loyers restent affichés malgré showUnitPriceWeb:false dans la config) qui101# sert de source de vérité, plus une grille de cartes dont on tire la photo102# de chaque unité (43/43 cartes avec image au relevé 2026-10-22).103# external_id = UUID unitId Livya (data-unit-id), identique à l'historique —104# zéro churn (recoupé 30/30 au 2026-10-22). Adresse/GPS : immeuble « 21105# mars » du flux RSC de la même page (toujours SSR) ; type d'unité dérivé106# des chambres (2 → 4½ — recoupé 30/30 avec l'historique).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import html as _html111import json112import re113import time114from urllib.parse import unquote115116from ..schema import Listing, infer_city117from .base import BaseConnector118119PLANS_URL = "https://app.livya.com/fr/trudel/projects/fdl/plans"120SITE_URL = PLANS_URL121SECTOR = "Vanier (Fleur de Lys)"122123# fragments RSC de Next.js : self.__next_f.push([1,"…"])124_FLIGHT_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')125126# vue tableau du DOM rendu (complète) + cartes de la grille (photos de plans)127_ROW_RE = re.compile(r'<tr data-unit-id="([0-9a-f-]{36})"')128_TH_RE = re.compile(r'<th[^>]*>(.*?)</th>', re.S)129_TD_RE = re.compile(r'<td[^>]*>(.*?)</td>', re.S)130_CARD_RE = re.compile(r'<div[^>]*data-unit-id="([0-9a-f-]{36})"')131_IMG_RE = re.compile(r'url=(https%3A%2F%2F[^&"]+)')132_COUNT_RE = re.compile(r'(\d+)\s*résultats?')133134_MOIS = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5,135 "juin": 6, "juillet": 7, "août": 8, "septembre": 9, "octobre": 10,136 "novembre": 11, "décembre": 12}137_DATE_FR_RE = re.compile(r"(\d{1,2})(?:er)?\s+([a-zûé]+)\s+(\d{4})", re.I)138139# scrolle tous les conteneurs à overflow interne (grille lazy-loadée : le140# scroll de la fenêtre ne charge rien — auto_scroll Scrapfly inopérant)141_SCROLL_JS = ("document.querySelectorAll('*').forEach(function(e){"142 "if(e.scrollHeight>e.clientHeight+10){e.scrollTop=e.scrollHeight}})")143144145def _cell_text(cell: str) -> str:146 return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", cell))).strip()147148149def _cell_num(s: str) -> float | None:150 digits = re.sub(r"[^\d.]", "", s or "")151 try:152 return float(digits) if digits else None153 except ValueError:154 return None155156157def _unit_type(beds: float | None) -> str:158 """Type dérivé des chambres (recoupé 30/30 avec l'historique JSON) :159 — -> Studio, 1 -> 3½, 2 -> 4½…"""160 if beds is None or beds < 1:161 return "Studio"162 return f"{int(beds) + 2}½"163164165class TrudelConnector(BaseConnector):166 source_id = "trudel"167 request_delay = 0.8168 max_units = 300 # garde-fou (990 unités au portefeuille)169170 # -- rendu navigateur -----------------------------------------------------------171 def get_rendered(self, url: str, wait_ms: int = 0) -> str:172 """HTML rendu Scrapfly, scroll des conteneurs internes (grille173 lazy-loadée). Surchargée (même nom que base) pour rester compatible174 avec le record/replay des fixtures — clé de rejeu = URL cible."""175 steps: list[dict] = []176 for _ in range(8):177 steps.append({"execute": {"script": _SCROLL_JS}})178 steps.append({"wait": 1200})179 html = self.get_scrapfly(url, render_js=True, asp=True,180 rendering_wait=wait_ms or 4000,181 js_scenario=steps)182 if not html:183 raise RuntimeError(f"Scrapfly : rendu vide — {url}")184 return html185186 def _render_ok(self, url: str) -> str:187 """Rendu dont la vue tableau est complète : le compteur « N résultats »188 doit être présent (sinon gabarit changé) et le nombre de lignes189 uniques du tableau doit l'atteindre — erreur franche après 3190 tentatives plutôt qu'un rendu tronqué qui dépublierait des unités."""191 last_err: Exception | None = None192 for attempt in range(3):193 html = self.get_rendered(url, wait_ms=4000)194 m = _COUNT_RE.search(_html.unescape(re.sub(r"<[^>]+>", " ", html)))195 if not m:196 last_err = RuntimeError(197 "app.livya.com (trudel) : compteur « N résultats » absent "198 f"du rendu — gabarit Livya changé ? ({url})")199 else:200 announced = int(m.group(1))201 uniques = len(set(_ROW_RE.findall(html)))202 if uniques >= announced:203 return html # announced == 0 : vrai zéro accepté204 last_err = RuntimeError(205 f"app.livya.com (trudel) : {uniques} ligne(s) unique(s) "206 f"pour {announced} annoncées — rendu incomplet ? ({url})")207 if attempt < 2:208 time.sleep(5 * (attempt + 1))209 assert last_err is not None210 raise last_err211212 # -- vue tableau du DOM rendu -> unités ------------------------------------------213 @staticmethod214 def _collect(html: str) -> dict[str, dict]:215 """Lignes du tableau (source de vérité) + photos des cartes de grille."""216 thead = re.search(r"<thead.*?</thead>", html, re.S)217 cols: dict[str, int] = {}218 if thead:219 for i, th in enumerate(_TH_RE.findall(thead.group(0))):220 t = _cell_text(th).lower()221 for key, label in (("name", "nom"), ("floor", "étage"),222 ("beds", "chambre"), ("baths", "salle"),223 ("area", "superficie"), ("price", "prix"),224 ("status", "statut")):225 if t.startswith(label):226 cols[key] = i227 if "name" not in cols or "status" not in cols:228 raise RuntimeError(229 "app.livya.com (trudel) : en-têtes du tableau introuvables "230 "(Nom/Statut) — gabarit Livya changé ?")231232 units: dict[str, dict] = {}233 rows = list(_ROW_RE.finditer(html))234 for i, m in enumerate(rows):235 end = rows[i + 1].start() if i + 1 < len(rows) else m.start() + 8000236 cells = [_cell_text(c) for c in237 _TD_RE.findall(html[m.start():min(end, m.start() + 8000)])]238239 def col(key: str) -> str:240 j = cols.get(key)241 return cells[j] if j is not None and j < len(cells) else ""242243 parsed = {244 "number": col("name").lstrip("#") or None,245 "floor": _cell_num(col("floor")),246 "beds": _cell_num(col("beds")),247 "baths": _cell_num(col("baths")),248 "area": _cell_num(col("area")),249 "price": _cell_num(col("price")),250 "status": col("status") or None,251 }252 u = units.setdefault(m.group(1), {})253 for k, v in parsed.items():254 if u.get(k) is None and v is not None:255 u[k] = v256257 # cartes de la grille : photo du plan/de l'unité type258 cards = [(x.start(), x.group(1)) for x in _CARD_RE.finditer(html)]259 for i, (pos, uid) in enumerate(cards):260 end = cards[i + 1][0] if i + 1 < len(cards) else pos + 9000261 im = _IMG_RE.search(html[pos:min(end, pos + 9000)])262 if im and uid in units and units[uid].get("image") is None:263 units[uid]["image"] = unquote(im.group(1))264 return units265266 # -- métadonnées de l'immeuble (flux RSC, toujours SSR) ---------------------------267 @staticmethod268 def _building(html: str) -> dict:269 """Immeuble « 21 mars » du flux RSC : adresse civique, ville, code270 postal, GPS — on préfère l'occurrence avec GPS non nul et on écarte271 les entrées techniques « plan d'ensemble »."""272 try:273 blob = "".join(274 json.loads(f'"{c}"') for c in _FLIGHT_RE.findall(html))275 except Exception:276 return {}277 dec = json.JSONDecoder()278 best: dict = {}279 for m in re.finditer(r'\{"buildingId"', blob):280 try:281 obj, _ = dec.raw_decode(blob[m.start():m.start() + 8000])282 except Exception:283 continue284 name = (obj.get("name") or "").lower()285 if "ensemble" in name or not (obj.get("address") or "").strip("- "):286 continue287 if obj.get("latitude") and obj.get("longitude"):288 return obj289 best = best or obj290 return best291292 def fetch(self) -> list[Listing]:293 html = self._render_ok(PLANS_URL)294 units = self._collect(html)295 cm = _COUNT_RE.search(_html.unescape(re.sub(r"<[^>]+>", " ", html)))296 if cm and int(cm.group(1)) and not units:297 raise RuntimeError(298 "app.livya.com (trudel) : aucune ligne d'unité dans le rendu "299 "— gabarit changé ?")300 building = self._building(html)301302 listings: list[Listing] = []303 for uid, u in list(units.items())[: self.max_units]:304 if not (u.get("status") or "").startswith("Disponible"):305 continue # « Réservé » & cie exclus306 listings.append(self._listing(uid, u, building))307 return listings308309 # -- une annonce par unité disponible ----------------------------------------------310 def _listing(self, uid: str, u: dict, building: dict) -> Listing:311 num = str(u.get("number") or "").strip()312 bname = (building.get("name") or "").strip() or "Le Vingt-et-un Mars"313314 address = ", ".join(x for x in (315 (building.get("address") or "").strip(),316 (building.get("city") or "").strip(),317 (building.get("postalCode") or "").strip()) if x)318319 price = u.get("price")320 price = float(price) if price and price > 1 else None321322 # « Disponible » ou « Disponible - 1 décembre 2026 » (date française)323 status = (u.get("status") or "").strip()324 availability = "Disponible"325 avail_date = None326 dm = _DATE_FR_RE.search(status)327 if dm and _MOIS.get(dm.group(2).lower()):328 avail_date = (f"{int(dm.group(3)):04d}-"329 f"{_MOIS[dm.group(2).lower()]:02d}-"330 f"{int(dm.group(1)):02d}")331 availability = f"Disponible à partir du {avail_date}"332333 beds, baths, area = u.get("beds"), u.get("baths"), u.get("area")334 unit_type = _unit_type(beds)335336 desc: list[str] = []337 if area and area > 0:338 desc.append(f"{int(area)} pi²")339 if beds:340 desc.append(f"{int(beds)} chambre(s)")341 if baths:342 desc.append(f"{int(baths)} salle(s) de bain")343 desc.append(f"Immeuble {bname} — Fleur de Lys")344345 details: dict = {}346 floor = u.get("floor")347 if floor and floor > 0:348 details["floor"] = int(floor)349350 images: list[str] = []351 if u.get("image"):352 images.append(u["image"])353354 try:355 lat = (float(building["latitude"])356 if building.get("latitude") else None)357 lng = (float(building["longitude"])358 if building.get("longitude") else None)359 except (TypeError, ValueError):360 lat = lng = None361362 return Listing(363 source=self.source_id,364 external_id=uid, # UUID Livya : stable, historique365 url=SITE_URL,366 title=f"Fleur de Lys ({bname}) — Unité {num}"367 f"{' (' + unit_type + ')' if unit_type else ''}",368 address=address or "550, boul. Wilfrid-Hamel, Québec",369 sector=SECTOR,370 city=infer_city(SECTOR, default="Québec"),371 unit_type=unit_type,372 bedrooms=beds if beds and beds > 0 else None,373 bathrooms=baths if baths and baths > 0 else None,374 price=price,375 price_label=f"{price:.0f} $ /mois" if price else "",376 availability=availability,377 availability_date=avail_date,378 area_sqft=area if area and area > 0 else None,379 description=" | ".join(desc),380 amenities=["Eau chaude incluse", "Air climatisé"],381 details=details,382 images=images[:12],383 lat=lat,384 lng=lng,385 )386