Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/logisquebec.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1713# 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/logisquebec.py : LogisQuébec (logisquebec.com) — portail locatif91# québécois (Réglisse Média). ~9 800 fiches location, province entière.92# Découverte par les sitemaps (99,7 % du parc vérifié vs compteurs des pages93# liste) : URLs de fiche « {type}-a-louer-{ville}-l###### ». Chaque fiche94# (SSR, Cloudflare tolérant) expose un JSON-LD complet : SingleFamilyResidence95# (adresse + code postal + GPS + téléphone) et Product (nom, description,96# offers.price, sku = id). Galerie lightGallery, disponibilité et97# caractéristiques actives (span .caracteristique-texte) dans le HTML.98# Fiche expirée -> HTTP 410 Gone (retrait immédiat). Cache détail avec TTL99# (les prix changent) via _detailutil.TtlDetailCache.100# Superficie : la fiche n'a AUCUN champ structuré (ni JSON-LD floorSize, ni101# caractéristique dédiée — vérifié 2026-08-18) ; seule l'extraction texte de102# finalize() (description/commodités) s'applique, ~26 % du parc en donne une.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import os107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type112from .base import BaseConnector113from . import _detailutil as du114115BASE = "https://www.logisquebec.com"116117# type d'URL -> (type d'unité par défaut, court terme ?) ; les slugs118# commerciaux (local-commercial, bureau, entrepot-industriel…) sont exclus119TYPES = {120 "appartement": ("", False),121 "condo": ("", False),122 "maison": ("Maison", False),123 "studio": ("Studio", False),124 "loft": ("Loft", False),125 "chambre-et-colocation": ("Chambre", False),126 "chalet": ("Chalet", False),127 "appartement-condo-court-terme": ("", True),128 "maison-court-terme": ("Maison", True),129 "chambre-court-terme": ("Chambre", True),130}131132_FICHE_RE = re.compile(133 r"^https://www\.logisquebec\.com/(" + "|".join(map(re.escape, TYPES)) +134 r")-a-louer-([a-z0-9_-]+)-l(\d+)$")135_LOC_RE = re.compile(r"<loc>(.*?)</loc>")136_PHOTO_RE = re.compile(r"https://i\.logisquebec\.com/i-a-louer/\d+/\d+/[^'\"]+")137_DISPO_RE = re.compile(r"Disponible à partir de\s*:?\s*\|\s*([^|]{1,60})")138139# Dimensionnement du budget détail : parc ~6 000 fiches, TTL 7 j, watch ~10140# passes/jour -> ~90 rafraîchissements/passe suffisent à tenir le TTL. 400141# laisse 4x de marge (poussées de nouvelles fiches) en ramenant le cycle de142# ~19 min à ~5 min. Les fiches JAMAIS VUES sont servies en premier (voir143# fetch) : aucune perte de volume, le parc se complète au même rythme.144DETAIL_LIMIT = int(os.environ.get("LOUKA_LOGISQUEBEC_DETAIL_LIMIT", "400"))145TTL_DAYS = float(os.environ.get("LOUKA_LOGISQUEBEC_TTL_DAYS", "7"))146MAX_FICHES = int(os.environ.get("LOUKA_LOGISQUEBEC_MAX", "0")) # 0 = tout147148149def _parse_fiche(html: str) -> dict:150 """Extrait le payload complet d'une page fiche LogisQuébec."""151 out: dict = {}152 for node in du.ld_nodes(html):153 t = node.get("@type") or ""154 if t == "SingleFamilyResidence":155 addr = node.get("address") or {}156 out["address"] = (addr.get("streetAddress") or "").strip()157 out["locality"] = (addr.get("addressLocality") or "").strip()158 out["postal_code"] = (addr.get("postalCode") or "").strip()159 geo = node.get("geo") or {}160 try:161 out["lat"] = float(geo.get("latitude"))162 out["lng"] = float(geo.get("longitude"))163 except (TypeError, ValueError):164 pass165 if node.get("telephone"):166 out["telephone"] = str(node["telephone"]).strip()167 rooms = node.get("numberOfRooms")168 if isinstance(rooms, (int, float)) and rooms > 0:169 out["rooms"] = int(rooms)170 elif t == "Product":171 out["title"] = (node.get("name") or "").strip()172 out["description"] = (node.get("description") or "").strip()[:6000]173 offers = node.get("offers") or {}174 try:175 out["price"] = float(str(offers.get("price")).replace(",", "."))176 except (TypeError, ValueError):177 pass178 if node.get("sku"):179 out["sku"] = str(node["sku"])180181 photos, seen = [], set()182 for u in _PHOTO_RE.findall(html):183 if "/thumbnail/" in u or u in seen:184 continue185 seen.add(u)186 photos.append(u)187 if photos:188 out["images"] = photos189190 # « Disponible à partir de : Immédiatement / 1er juillet… » (texte aplati)191 flat = du.flatten(html)192 m = _DISPO_RE.search(flat)193 if m:194 out["availability"] = m.group(1).strip(" .")195196 # caractéristiques ACTIVES = items possédant un span .caracteristique-texte197 # (les items sans texte sont la légende inactive des icônes)198 soup = BeautifulSoup(html, "html.parser")199 amenities = []200 for it in soup.select(".caracteristique-item"):201 if it.select_one(".caracteristique-texte") is None:202 continue203 label = it.get_text(" ", strip=True)204 label = re.sub(r"\s+", " ", label)205 # le titre est dupliqué dans le texte : « 2 chambres 2 chambres »206 half = len(label) // 2207 if len(label) % 2 == 1 and label[:half] == label[half + 1:]:208 label = label[:half]209 if label and label not in amenities:210 amenities.append(label)211 if amenities:212 out["amenities"] = amenities213214 vt = du.virtual_tour(html) # lien Matterport/iGUIDE… si la fiche en a un215 if vt:216 out["virtual_tour"] = vt217 return out218219220class LogisQuebecConnector(BaseConnector):221 source_id = "logisquebec"222 request_delay = 0.5223224 # -- découverte ------------------------------------------------------------225 def _fiche_urls(self) -> list[tuple[str, str, str, str]]:226 """(url, type_slug, ville_slug, id) des fiches location résidentielles."""227 index = self.get(f"{BASE}/sitemap.xml").text228 subs = [u for u in _LOC_RE.findall(index) if "/sitemap/" in u]229 out, seen = [], set()230 for sub in subs:231 try:232 xml = self.get(sub).text233 except Exception:234 continue235 for u in _LOC_RE.findall(xml):236 m = _FICHE_RE.match(u)237 if m and m.group(3) not in seen:238 seen.add(m.group(3))239 out.append((u, m.group(1), m.group(2), m.group(3)))240 return out241242 # -- construction ----------------------------------------------------------243 def _to_listing(self, url: str, type_slug: str, payload: dict) -> Listing | None:244 if not payload or payload.get("gone"):245 return None246 eid = payload.get("sku") or url.rsplit("-l", 1)[-1]247 default_type, court_terme = TYPES[type_slug]248249 title = payload.get("title") or ""250 unit_type = normalize_unit_type(title)251 if not re.match(r"^\d½|^6½\+$", unit_type or ""):252 unit_type = ""253 if not unit_type and payload.get("rooms"):254 n = payload["rooms"]255 unit_type = "6½+" if n >= 6 else f"{n}½"256 if not unit_type: # « 2 chambres » des caractéristiques257 for a in payload.get("amenities") or []:258 if re.match(r"^\d+ chambres?$", a):259 unit_type = normalize_unit_type(a)260 break261 if not unit_type:262 unit_type = default_type263264 locality = payload.get("locality") or ""265 m = re.match(r"^(.*?)\s*\((.+)\)\s*$", locality)266 sector, city = (m.group(1), m.group(2)) if m else ("", locality)267268 price = payload.get("price")269 # clés canoniques (mêmes noms que normalize.extract_details : le270 # merge_details de finalize() fusionne contact{} clé par clé)271 details: dict = {}272 if payload.get("postal_code"):273 details["postal_code"] = payload["postal_code"]274 if payload.get("telephone"):275 details["contact"] = {"phone": payload["telephone"]}276 if payload.get("rooms"):277 details["rooms"] = payload["rooms"] # numberOfRooms (JSON-LD)278 if court_terme:279 details["Location court terme"] = "oui"280 if payload.get("virtual_tour"):281 details["virtual_tour"] = payload["virtual_tour"]282283 amenities = payload.get("amenities") or []284 lst = Listing(285 source=self.source_id,286 external_id=str(eid),287 url=url,288 title=title,289 address=payload.get("address") or "",290 sector=sector,291 city=city,292 unit_type=unit_type,293 price=price,294 price_label=(f"{price:,.0f} $/mois".replace(",", " ") if price else ""),295 availability=payload.get("availability") or "",296 description=payload.get("description") or "",297 amenities=amenities,298 details=details,299 images=payload.get("images") or [],300 lat=payload.get("lat"),301 lng=payload.get("lng"),302 )303 low = [a.lower() for a in amenities]304 if any("animaux accept" in a for a in low):305 lst.pets = "oui"306 if "meublé" in low:307 lst.furnished = True308 return lst309310 def fetch(self) -> list[Listing]:311 fiches = self._fiche_urls()312 if MAX_FICHES:313 fiches = fiches[:MAX_FICHES]314 cache = du.TtlDetailCache(self, budget=DETAIL_LIMIT, ttl_days=TTL_DAYS)315 # priorité du budget aux fiches jamais visitées (tri stable) : les316 # nouveautés sont toujours captées au premier passage, le reste du317 # budget sert au rafraîchissement TTL318 seen = {r["external_id"] for r in cache.con.execute(319 "SELECT external_id FROM detail_cache WHERE source=?",320 (self.source_id,))}321 fiches.sort(key=lambda f: f[3] in seen)322 out: list[Listing] = []323 try:324 for url, type_slug, _ville, eid in fiches:325 payload = cache.get(eid, url, _parse_fiche)326 if payload is None: # jamais visitée + budget épuisé :327 continue # captée à une prochaine synchronisation328 lst = self._to_listing(url, type_slug, payload)329 if lst is not None:330 out.append(lst)331 finally:332 cache.close()333 return out334