Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/logis_experts.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0813# Last Modified : 2026-08-1814#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/logis_experts.py : connecteur Logis-Experts (logis-experts.com)91# Gestionnaire-constructeur, Québec + Lévis (~60 immeubles, ~370 unités).92#93# Site refait en Next.js (App Router) en novembre 2026 : l'ancienne API JSON94# GET /api/search a disparu (404). Les données vivent maintenant dans le flux95# RSC des pages (scripts `self.__next_f.push([1,"…"])`) :96# /appartements -> tuiles d'immeubles, chacune avec son `handle`97# /immeuble/<handle> -> props `"logements":[{numero, url, crm, type,98# typeCle, etage, superficie, prix, libre,99# disponible, inclusions, photos, plan}]`100# + JSON-LD ApartmentComplex (adresse, code101# postal, coordonnées, secteur, photos, animaux)102# Une page d'immeuble porte TOUTES ses unités à louer avec prix, superficie103# et disponibilité : plus aucune visite de page détail par unité.104# Pas de zéro silencieux : structure non reconnue = erreur franche.105# -----------------------------------------------------------------------------106from __future__ import annotations107108import json109import re110import time111112from ..schema import Listing, infer_city113from .base import BaseConnector114115BASE = "https://logis-experts.com"116LIST_URL = f"{BASE}/appartements"117118# Ville publiée par le site -> nom d'affichage119CITY_MAP = {120 "quebec": "Québec", "québec": "Québec", "levis": "Lévis", "lévis": "Lévis",121 "charny": "Lévis",122 "saint-augustin-de-desmaures": "Saint-Augustin-de-Desmaures",123}124125# « 3.5+office » -> « 3½ », « maisondeville2chambres » -> « Maison », etc.126_TYPE_DEMI_RE = re.compile(r"^(\d)\.5")127_RSC_RE = re.compile(r'self\.__next_f\.push\(\[1,"(.*?)"\]\)</script>', re.S)128_HANDLE_RE = re.compile(r'"handle":"([^"]+)"')129_FLOOR_RE = re.compile(r"^(\d+)e?r?\s*étage", re.I)130_JSON = json.JSONDecoder()131132133def _unit_type(raw: str) -> str:134 s = (raw or "").strip().lower()135 m = _TYPE_DEMI_RE.match(s)136 if m:137 return f"{m.group(1)}½"138 if "maisondeville" in s:139 return "Maison"140 if "loft" in s:141 return "Loft"142 if "studio" in s or "bachelor" in s:143 return "Studio"144 if "chambre" in s:145 return "Chambre"146 return raw.strip()147148149def _rsc(html: str) -> str:150 """Concatène le flux RSC d'une page Next.js (chaînes JS échappées)."""151 out = []152 for part in _RSC_RE.findall(html):153 try:154 out.append(json.loads('"' + part + '"'))155 except ValueError:156 continue157 return "".join(out)158159160def _complex_ld(flux: str) -> dict:161 """Bloc JSON-LD « ApartmentComplex » de la page d'immeuble ({} si absent)."""162 pos = flux.find('{"@context"')163 while pos >= 0:164 try:165 ld, _ = _JSON.raw_decode(flux, pos)166 except ValueError:167 ld = None168 if isinstance(ld, dict):169 for obj in ld.get("@graph") or [ld]:170 if isinstance(obj, dict) and obj.get("@type") == "ApartmentComplex":171 return obj172 pos = flux.find('{"@context"', pos + 5)173 return {}174175176class LogisExpertsConnector(BaseConnector):177 source_id = "logis_experts"178 request_delay = 0.6179180 def _page(self, url: str) -> str:181 """Flux RSC d'une page ; un hoquet isolé (réseau, 5xx, flux vide) est182 retenté deux fois avant l'erreur franche."""183 last: Exception | None = None184 for attempt in range(3):185 try:186 flux = _rsc(self.get(url).text)187 if flux:188 return flux189 last = RuntimeError(f"flux RSC vide — {url}")190 except Exception as exc: # noqa: BLE001191 last = exc192 if attempt < 2:193 time.sleep(3 * (attempt + 1))194 raise RuntimeError(f"logis_experts : page illisible — {url} ({last})")195196 def _building(self, handle: str) -> list[Listing]:197 page_url = f"{BASE}/immeuble/{handle}"198 flux = self._page(page_url)199 start = flux.find('"logements":[')200 if start < 0:201 raise RuntimeError(202 f"logis_experts : gabarit remanié, « logements » introuvable — {page_url}")203 try:204 units, _ = _JSON.raw_decode(flux, start + len('"logements":'))205 except ValueError as exc:206 raise RuntimeError(207 f"logis_experts : liste des logements illisible — {page_url} ({exc})")208209 ld = _complex_ld(flux)210 addr = ld.get("address") or {}211 geo = ld.get("geo") or {}212 civic = (addr.get("streetAddress") or "").strip()213 zipcode = (addr.get("postalCode") or "").strip()214 city_raw = (addr.get("addressLocality") or "").strip()215 city = CITY_MAP.get(city_raw.lower(), city_raw)216 sector = ((ld.get("containedInPlace") or {}).get("name") or "").strip()217 if city_raw.lower() == "charny" and not sector:218 sector = "Charny"219 full_addr = ", ".join(x for x in (civic, city, zipcode) if x)220 b_name = (ld.get("name") or civic or handle).strip()221 lat, lng = geo.get("latitude"), geo.get("longitude")222 b_images = [p.get("url") for p in (ld.get("photo") or [])223 if isinstance(p, dict) and p.get("url")]224 b_amenities = [f.get("name") for f in (ld.get("amenityFeature") or [])225 if isinstance(f, dict) and f.get("name") and f.get("value", True)]226 pets_allowed = ld.get("petsAllowed")227 pets = None if pets_allowed is None else ("conditions" if pets_allowed else "non")228229 out: list[Listing] = []230 for u in units:231 if not isinstance(u, dict):232 continue233 num = str(u.get("numero") or "").strip()234 ext_id = str(u.get("crm") or f"{handle}-{num}")235 rel = u.get("url") or f"/immeuble/{handle}/appartement/{num}"236 price = u.get("prix")237 price = float(price) if isinstance(price, (int, float)) and price else None238 area = u.get("superficie")239 area = float(area) if isinstance(area, (int, float)) and area else None240241 # inclusions : paires [libellé, valeur] ; « Frais d'énergie » en tête242 amenities: list[str] = []243 phrases: list[str] = []244 if area:245 phrases.append(f"Superficie de {area:.0f} pi².")246 etage = (u.get("etage") or "").strip()247 details: dict = {}248 m = _FLOOR_RE.match(etage)249 if m:250 details["floor"] = int(m.group(1))251 phrases.append("Au 1er étage." if m.group(1) == "1" else f"Au {m.group(1)}e étage.")252 elif etage:253 phrases.append("Au rez-de-chaussée." if "rez" in etage.lower() else f"Étage : {etage}.")254 if u.get("orientation"):255 phrases.append(f"Orientation : {u['orientation']}.")256 for pair in u.get("inclusions") or []:257 if not (isinstance(pair, list) and len(pair) == 2):258 continue259 label, value = str(pair[0]).strip(), str(pair[1]).strip()260 if not label or not value:261 continue262 if "énergie" in label.lower():263 amenities.insert(0, value) # ex. « Chauffé & Éclairé »264 phrases.append(f"{label} : {value}.")265 elif value.lower() == "oui":266 amenities.append(label)267 phrases.append(f"{label}.")268 elif value.lower() != "non":269 amenities.append(f"{label} : {value}")270 phrases.append(f"{label} : {value}.")271 for a in b_amenities:272 if a not in amenities:273 amenities.append(a)274 if u.get("moisGratuits"):275 phrases.append(f"Promotion : {u['moisGratuits']} mois gratuit(s).")276277 # photos de l'unité (pleine résolution), plan, puis photos de l'immeuble278 images: list[str] = []279 for p in u.get("photos") or []:280 src = p.get("url") if isinstance(p, dict) else None281 if src and src not in images:282 images.append(src)283 plan = u.get("plan")284 plan_url = plan.get("url") if isinstance(plan, dict) else (plan if isinstance(plan, str) else None)285 if plan_url and plan_url.startswith("http") and plan_url not in images:286 images.append(plan_url)287 images += [x for x in b_images if x not in images]288289 if u.get("libre"):290 availability = "Libre immédiatement"291 else:292 availability = str(u.get("disponible") or "").strip()293294 out.append(Listing(295 source=self.source_id,296 external_id=ext_id,297 url=BASE + rel if rel.startswith("/") else rel,298 title=f"{b_name} — app. {num}" if num else b_name,299 address=full_addr,300 sector=sector,301 city=infer_city(sector, default=city or "Québec"),302 unit_type=_unit_type(u.get("typeCle") or u.get("type") or ""),303 price=price,304 price_label=f"{price:.0f} $ /mois" if price else "",305 availability=availability,306 area_sqft=area,307 pets=pets,308 description=" ".join(phrases),309 amenities=amenities,310 details=details,311 images=images[:20],312 lat=float(lat) if lat else None,313 lng=float(lng) if lng else None,314 ))315 return out316317 def fetch(self) -> list[Listing]:318 flux = self._page(LIST_URL)319 handles = list(dict.fromkeys(_HANDLE_RE.findall(flux)))320 if not handles:321 raise RuntimeError(322 "logis_experts : gabarit remanié, aucun immeuble dans /appartements")323 listings: list[Listing] = []324 for handle in handles:325 listings.extend(self._building(handle))326 if not listings:327 raise RuntimeError(328 f"logis_experts : {len(handles)} immeubles lus mais aucune unité "329 "à louer — structure des pages d'immeuble à revoir")330 return listings331