Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gestion_tb.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-09-0414#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/gestion_tb.py : connecteur Gestion TB (Drummondville)91# Portail d'annonces appartementstb.ca (aussi servi sur92# gestiontb.ca/logements-a-louer) : page unique Nuxt SSR (constructeur93# GoHighLevel). Tout le contenu est dans le payload JSON94# <script id="__NUXT_DATA__"> (format « devalue » : tableau plat dont les95# valeurs se référencent par index — patron voisin du payload flight96# Next.js de msi.py). L'arbre de la page contient des sections par97# typologie (« Section 3 1/2 »…) et une colonne (col) par logement dont le98# TITRE est l'adresse (« 900-3 RUE ALEXANDRE ») avec des sous-titres99# (secteur, ville, disponibilité, étage, prix « 900 $ / mois ») et un100# carrousel de photos (sliderList). Pas de robots.txt (tout permis).101# Une seule requête HTTP par synchronisation.102# Refonte 2026 (~2026-09) : la page est reconstruite avec des blocs103# c-custom-code autonomes; les logements sont un tableau JSON embarqué104# « window.GTB_LOGEMENTS = [...] » (champs structurés : prix, adresse,105# ville, chambres, sallesDeBain, disponibilite, photos…). Fiche ouverte106# en modal, deep-link « #logement=<id> ». L'ancien parcours de l'arbre107# d'éléments (colonnes) est conservé en secours si le tableau disparaît.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import json112import re113114from ..schema import Listing, strip_accents115from .base import BaseConnector116117PORTAIL = "https://appartementstb.ca"118119_NUXT_RE = re.compile(120 r'<script[^>]+id="__NUXT_DATA__"[^>]*>(.*?)</script>', re.S)121# enveloppes « devalue » de Nuxt 3 : ["Reactive", 12] -> valeur à l'index 12122_WRAPPERS = {"Reactive", "ShallowReactive", "Ref", "ShallowRef",123 "EmptyRef", "EmptyShallowRef"}124# titres de colonnes génériques du constructeur (pas des logements)125_GENERIC_COL = re.compile(r"^\s*\d+(?:st|nd|rd|th)?\s*Column\s*$", re.I)126# graphies de villes vues sur le portail -> toponymes officiels127_CITY_CANON = {128 "ndbc": "Notre-Dame-du-Bon-Conseil",129 "notre-dame-du-bon-conseil": "Notre-Dame-du-Bon-Conseil",130 "saint-leonard d'aston": "Saint-Léonard-d'Aston",131 "saint-léonard d'aston": "Saint-Léonard-d'Aston",132 "saint-cyrille": "Saint-Cyrille-de-Wendover",133}134_TAG_RE = re.compile(r"<[^>]+>")135136137def _decode_nuxt(html: str):138 """Décode le payload __NUXT_DATA__ (tableau plat auto-référencé)."""139 m = _NUXT_RE.search(html)140 if not m:141 return None142 data = json.loads(m.group(1))143144 def res(i, depth=0):145 if not isinstance(i, int) or i < 0 or i >= len(data) or depth > 200:146 return i147 v = data[i]148 if isinstance(v, dict):149 return {k: res(ix, depth + 1) for k, ix in v.items()}150 if isinstance(v, list):151 if len(v) == 2 and isinstance(v[0], str) and v[0] in _WRAPPERS:152 return res(v[1], depth + 1)153 return [res(ix, depth + 1) for ix in v]154 return v155156 return res(0)157158159def _lines(html_fragment: str) -> list[str]:160 """Un fragment riche (« <h2>…</h2><h2>…</h2> ») -> lignes de texte."""161 out = []162 for piece in re.split(r"</(?:h\d|p|div|li)>|<br\s*/?>", html_fragment or ""):163 t = re.sub(r"\s+", " ", _TAG_RE.sub(" ", piece)).replace("\u202f", " ").strip()164 if t:165 out.append(t)166 return out167168169class GestionTBConnector(BaseConnector):170 source_id = "gestion_tb"171 request_delay = 0.7172173 # -- parcours de l'arbre d'éléments -------------------------------------------174 @staticmethod175 def _collect(el_id: str, idx: dict, subs: list[str], imgs: list[str],176 depth: int = 0) -> None:177 """Descend un élément : accumule textes des sous-titres et photos."""178 el = idx.get(el_id)179 if not isinstance(el, dict) or depth > 12:180 return181 extra = el.get("extra") if isinstance(el.get("extra"), dict) else {}182 tag = str(el.get("tagName") or "")183 if tag in ("c-sub-heading", "c-heading", "c-paragraph"):184 for t in _lines(((extra.get("text") or {}).get("value") or "")):185 # recolle les libellés coupés sur deux titres186 # (« Secteur Notre-Dame-Du- » + « Bon-Conseil »)187 if subs and subs[-1].endswith("-"):188 subs[-1] += t189 else:190 subs.append(t)191 if tag == "c-image-slider":192 for s in ((extra.get("sliderList") or {}).get("value") or []):193 u = str((s or {}).get("backgroundImage") or "")194 if u.startswith("http") and u not in imgs:195 imgs.append(u)196 for cid in el.get("child") or []:197 if isinstance(cid, str):198 GestionTBConnector._collect(cid, idx, subs, imgs, depth + 1)199200 def fetch(self) -> list[Listing]:201 html = self.get(PORTAIL + "/").text202 root = _decode_nuxt(html)203 try:204 elements = root["data"]["pageData"]["elements"]205 except (TypeError, KeyError):206 return []207 listings = self._from_gtb_logements(elements)208 if listings:209 return listings210 return self._from_cols(elements)211212 # -- refonte 2026 : tableau JSON « window.GTB_LOGEMENTS » -----------------213 def _from_gtb_logements(self, elements: list) -> list[Listing]:214 data: list = []215 for el in elements:216 if not isinstance(el, dict) or el.get("tagName") != "c-custom-code":217 continue218 extra = el.get("extra") if isinstance(el.get("extra"), dict) else {}219 code = str(((extra.get("customCode") or {}).get("value") or {})220 .get("rawCustomCode") or "")221 m = re.search(r"window\.GTB_LOGEMENTS\s*=\s*\[", code)222 if not m:223 continue224 try:225 data, _ = json.JSONDecoder().raw_decode(code, m.end() - 1)226 except ValueError:227 continue228 break229230 listings: list[Listing] = []231 for d in data:232 if not isinstance(d, dict) or d.get("actif") is not True:233 continue234 ext_id = str(d.get("id") or "").strip()235 price = d.get("prix")236 if not ext_id or not isinstance(price, (int, float)):237 continue238239 unit_type = str(d.get("typeAffiche") or d.get("type") or "").strip()240 address = str(d.get("adresse") or "").strip()241 city = str(d.get("ville") or "Drummondville").strip().replace("’", "'")242 city = _CITY_CANON.get(243 re.sub(r"\s+", " ", city).lower().replace("st-", "saint-"),244 city)245 sector = str(d.get("secteurAffiche") or d.get("secteur")246 or "").strip().replace("’", "'")247 key = strip_accents(re.sub(r"[\s-]+", " ", sector).lower()) \248 .replace("st ", "saint ")249 if key == strip_accents(re.sub(r"[\s-]+", " ", city).lower()):250 sector = ""251252 dispo = d.get("disponibilite") if isinstance(253 d.get("disponibilite"), dict) else {}254 availability = str(dispo.get("libelle") or "").strip()255256 animaux = d.get("animaux") if isinstance(d.get("animaux"), dict) else {}257 pets = None258 if animaux:259 allowed = [bool(animaux.get("chat")), bool(animaux.get("chien"))]260 pets = "oui" if all(allowed) else \261 ("conditions" if any(allowed) else "non")262263 amenities = [str(c).strip() for c in (d.get("caracteristiques") or [])264 if str(c).strip()]265266 imgs: list[str] = []267 for u in [d.get("photoPrincipale"), *(d.get("photos") or [])]:268 u = str(u or "")269 if u.startswith("http") and u not in imgs:270 imgs.append(u)271272 details: dict = {}273 floor = str(d.get("etage") or "").strip()274 if floor:275 details["floor_label"] = floor276 if isinstance(d.get("stationnements"), (int, float)):277 details["parking_count"] = d["stationnements"]278279 title = " ".join(x for x in (unit_type, address) if x)280 title = f"{title} à {int(price)}$" if title else str(d.get("titre") or "")281 description = str(d.get("description") or "").strip()282 if not description:283 description = " — ".join(284 x for x in (str(d.get("titre") or "").strip(),285 f"Secteur {sector}" if sector else "",286 availability, *amenities) if x)[:600]287288 listings.append(Listing(289 source=self.source_id,290 external_id=ext_id,291 url=f"{PORTAIL}/#logement={ext_id}",292 title=title,293 address=address,294 sector=sector,295 city=city,296 unit_type=unit_type,297 price=float(price),298 price_label=f"{int(price)} $ / mois",299 bedrooms=d.get("chambres") if isinstance(300 d.get("chambres"), (int, float)) else None,301 bathrooms=d.get("sallesDeBain") if isinstance(302 d.get("sallesDeBain"), (int, float)) else None,303 availability=availability,304 pets=pets,305 description=description,306 amenities=amenities,307 details=details,308 images=imgs[:15],309 ))310 return listings311312 # -- ancien format (page constructeur en colonnes, avant refonte 2026) ----313 def _from_cols(self, elements: list) -> list[Listing]:314 idx = {e.get("id"): e for e in elements if isinstance(e, dict)}315316 # sections par typologie, dans l'ordre du document317 listings: list[Listing] = []318 section_type = ""319 card_ids: set[str] = set()320 for el in elements:321 if not isinstance(el, dict):322 continue323 if el.get("type") == "section":324 m = re.search(r"Section\s+(\d)\s*1/2",325 str(el.get("title") or ""), re.I)326 section_type = f"{m.group(1)}½" if m else ""327 continue328 if el.get("type") != "col":329 continue330 title = str(el.get("title") or "").strip()331 if not title or _GENERIC_COL.match(title):332 continue333 col_id = str(el.get("id") or "")334 if not col_id or col_id in card_ids:335 continue336337 subs: list[str] = []338 imgs: list[str] = []339 self._collect(col_id, idx, subs, imgs)340 blob = " | ".join(subs)341 if "$" not in blob and not re.search(r"disponible", blob, re.I):342 continue # colonne décorative, pas une annonce343 card_ids.add(col_id)344345 # prix : sous-titre « 900 $ / mois », sinon « … à 900$ » du titre346 price_label = ""347 for t in subs:348 if re.search(r"\d\s*\$\s*/\s*mois", t):349 price_label = t350 break351 if not price_label:352 m = re.search(r"à\s+([\d\s,]+\$)", blob)353 if m:354 price_label = m.group(1).strip()355356 # typologie : en-tête de carte (« 3 ½ rue Alexandre à 900$ »),357 # sinon la section courante358 unit_type = section_type359 m = re.search(r"(\d)\s*½", blob)360 if m:361 unit_type = f"{m.group(1)}½"362363 # en-tête affiché de la carte (« 3 ½ rue Alexandre à 900$ ») —364 # plus fiable que le titre interne du constructeur, parfois365 # périmé quand une carte est dupliquée dans l'éditeur366 headline = ""367 for t in subs:368 if re.search(r"\d\s*½.*\$|\$.*\d\s*½", t) or \369 re.search(r"à\s+(?:partir\s+de\s+)?[\d\s,]+\$", t):370 headline = t371 break372373 # disponibilité (texte source)374 availability = ""375 m = re.search(r"(?:\d+\s+)?Disponible[^|]*", blob, re.I)376 if m:377 availability = m.group(0).strip()378379 # ville : mention entre parenthèses « (Drummondville) »,380 # sinon secteur NDBC ; défaut = Drummondville (siège du parc)381 city = "Drummondville"382 m = re.search(r"\(\s*([A-ZÀ-Ü][^)|]{2,35}?)\s*\)", blob)383 if m:384 city = m.group(1).strip()385 elif re.search(r"Bon[\s-]Conseil|NDBC", blob + " " + title, re.I):386 city = "Notre-Dame-du-Bon-Conseil"387 city = _CITY_CANON.get(388 re.sub(r"\s+", " ", city).lower().replace("st-", "saint-"),389 city)390391 # secteur : ligne « Secteur … »392 sector = ""393 m = re.search(r"Secteur\s+([^|(]+)", blob, re.I)394 if m:395 sector = m.group(1).strip().rstrip(" -–")396 if sector.lower() == city.lower():397 sector = ""398399 # étage : sous-titre « 1er étage »400 details: dict = {}401 m = re.search(r"\b(\d+(?:er|e|ème)\s+étage)\b", blob, re.I)402 if m:403 details["floor_label"] = m.group(1)404405 listings.append(Listing(406 source=self.source_id,407 external_id=col_id.removeprefix("col-"),408 url=f"{PORTAIL}/#{col_id}",409 title=headline or title,410 address="", # jamais affichée en entier sur le portail411 sector=sector,412 city=city,413 unit_type=unit_type,414 price_label=price_label,415 availability=availability,416 description=" — ".join(dict.fromkeys(subs))[:600],417 details=details,418 images=imgs[:15],419 ))420 return listings421