Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/logisquebec.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1313# Last Modified : 2026-08-1914#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/logisquebec.py : LogisQuébec (section « à vendre » seulement)91#92# Portail québécois surtout connu pour la location, mais avec ~4 20093# propriétés À VENDRE (particuliers + agences syndiquées, ex. Proprio Direct).94# Pagination serveur classique /a-vendre/{page} (10 cartes/page, ~420 pages),95# cartes riches (type, prix, rue, ville, extrait, photo). La fiche détail96# (JSON-LD SingleFamilyResidence + Product) fournit adresse exacte, code97# postal, géoloc, description et le n° MLS/Centris quand l'annonce vient98# d'une agence ; galerie i.logisquebec.com séquentielle.99#100# source_id « logis_ag_quebec » : l'infixe _ag_ active la dédup Centris —101# les annonces d'agences déjà couvertes (même n° MLS) sont masquées, les102# annonces de particuliers (id interne vNNNNNN) restent toujours visibles.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import html as _html107import os108import re109110from .base import BaseConnector111from . import _detailutil as du112from ..normalize import parse_price113from ..schema import PropertyListing114115SITE = "https://www.logisquebec.com"116DETAIL_LIMIT = int(os.environ.get("IMMOKA_LOGISQC_DETAIL_LIMIT",117 os.environ.get("IMMOKA_DETAIL_LIMIT", "300")))118AGENCY = "LogisQuébec"119120_PAGE_MAX_RE = re.compile(r'href="/a-vendre/(\d+)"')121_CARD_RE = re.compile(122 r'<a href="/([a-z0-9_-]+?)-a-vendre-([a-z0-9_-]+)-v(\d+)"[^>]*'123 r'class="property-result[^"]*"(.*?)</a>', re.S | re.I)124_MLS_RE = re.compile(r"(?:MLS|Centris)[^0-9]{0,15}(\d{7,9})", re.I)125# galerie : la VRAIE galerie est le tableau JS lightGallery « dynamicimgEl »126# dont les src sont RELATIFS (i-a-vendre/<uid>/<vid>/N.jpg, sans https://) —127# un motif ancré sur le domaine ne voit que la photo 1 (og:image), les128# vignettes /thumbnail/ et les couvertures des « propriétés similaires »129# (autres vid). D'où le motif src: + repli absolu filtré sur le vid canonique.130_GALLERY_RE = re.compile(131 r"src:\s*'(?:https://i\.logisquebec\.com/)?(i-a-vendre/[^']+?\.jpe?g)'", re.I)132_PHOTO_RE = re.compile(133 r"https://i\.logisquebec\.com/(i-a-vendre/(\d+)/(\d+)/([^\"'\\ ]+\.jpe?g))", re.I)134_CANON_RE = re.compile(r'canonical"\s+href="[^"]*-v(\d+)"')135_IMG_HOST = "https://i.logisquebec.com/"136137138class LogisQuebecConnector(BaseConnector):139 source_id = "logis_ag_quebec"140 request_delay = 0.3141 max_pages = 600 # garde-fou (10 cartes/page)142143 def fetch(self) -> list[PropertyListing]:144 by_id: dict[str, PropertyListing] = {}145 last_page, dry = None, 0146 for page in range(1, self.max_pages + 1):147 url = f"{SITE}/a-vendre" + (f"/{page}" if page > 1 else "")148 try:149 html = self.get(url).text150 except Exception:151 break152 if last_page is None:153 nums = [int(n) for n in _PAGE_MAX_RE.findall(html)]154 last_page = max(nums) if nums else 1155 before = len(by_id)156 for lst in self._cards(html):157 by_id.setdefault(lst.external_id, lst)158 dry = dry + 1 if len(by_id) == before else 0159 if dry >= 3 or page >= (last_page or 1):160 break161 listings = list(by_id.values())162 # v2 : galerie filtrée sur le vid de la fiche (v1 mélangeait vignettes163 # et « propriétés similaires »), specs du tableau Libellé|Valeur,164 # description HTML complète, garde-fou GPS Québec. NB : certaines165 # fiches encore listées répondent 410 (fantômes côté site) — l'échec166 # est mis en cache {} et ne sera retenté qu'au prochain bump de clé.167 du.enrich(self, listings, DETAIL_LIMIT, parse_logisqc_detail, key="v2")168 # n° MLS connu -> external_id (dédup Centris contre les bannières)169 out: dict[str, PropertyListing] = {}170 for lst in listings:171 mls = str(lst.details.pop("_mls", "") or "")172 if mls:173 lst.mls = mls174 lst.external_id = mls175 addr = lst.details.pop("_addr", "")176 if addr:177 lst.address = addr178 lst.title = addr179 city = lst.details.pop("_city", "")180 if city:181 lst.city = city182 out.setdefault(lst.external_id, lst)183 return list(out.values())184185 # -- cartes de résultats ----------------------------------------------------186 def _cards(self, html: str):187 for m in _CARD_RE.finditer(html):188 type_s, city_s, vid, blk = m.groups()189190 def grab(pat: str) -> str:191 g = re.search(pat, blk, re.S)192 return _html.unescape(re.sub(r"<[^>]+>", " ", g.group(1))).strip() if g else ""193194 prix = grab(r'class="prix-valeur">([^<]+)<')195 rue = grab(r'class="adresse-rue">([^<]+)<')196 ville = grab(r'class="adresse-ville">([^<]+)<')197 typ = grab(r'class="box-result-unit-12A">([^<]+)<')198 desc = grab(r'class="box-result-unit-3A">(.*?)</div>')199 img = re.search(r'src="(https://i\.logisquebec\.com/[^"]+)"', blk)200 addr = " ".join(filter(None, [rue])) if rue and rue != "enclavé" else ""201 yield PropertyListing(202 source=self.source_id, external_id=vid,203 url=f"{SITE}/{type_s}-a-vendre-{city_s}-v{vid}",204 title=addr or f"{typ} — {ville}",205 address=addr,206 city=ville,207 property_type=typ or type_s.replace("-", " "),208 price=parse_price(prix),209 price_label=prix,210 description=desc[:1000],211 images=[img.group(1)] if img else [],212 agency=AGENCY,213 )214215216# ---------------------------------------------------------------------------217def parse_logisqc_detail(html: str) -> dict:218 """JSON-LD SingleFamilyResidence (adresse/géo/postal) + Product (prix,219 description) ; n° MLS dans le HTML ; galerie i.logisquebec.com complète."""220 out: dict = {}221 details: dict = {}222 for node in du.ld_nodes(html):223 t = node.get("@type")224 if t in ("SingleFamilyResidence", "Residence", "Apartment"):225 addr = node.get("address") or {}226 if addr.get("streetAddress"):227 details["_addr"] = str(addr["streetAddress"])228 if addr.get("addressLocality"):229 details["_city"] = str(addr["addressLocality"])230 if addr.get("postalCode"):231 details["postal_code"] = str(addr["postalCode"])232 geo = node.get("geo") or {}233 try:234 lat, lng = float(geo["latitude"]), float(geo["longitude"])235 # le géocodage du site déraille parfois (Guadeloupe, Floride…) :236 # on ne garde que des coordonnées plausibles pour le Québec237 if 44.0 <= lat <= 63.0 and -80.5 <= lng <= -56.0:238 out["lat"], out["lng"] = lat, lng239 except (KeyError, TypeError, ValueError):240 pass241 if node.get("numberOfRooms"):242 details["Nombre de pièces"] = node["numberOfRooms"]243 elif t == "Product":244 if node.get("description"):245 out["description"] = _html.unescape(str(node["description"])).strip()[:4000]246 offers = node.get("offers") or {}247 p = offers.get("price") if isinstance(offers, dict) else None248 try:249 out["price"] = float(p)250 out["price_label"] = f"{float(p):,.0f} $".replace(",", " ")251 except (TypeError, ValueError):252 pass253254 mm = _MLS_RE.search(html)255 if mm:256 details["_mls"] = mm.group(1)257258 # galerie : tableau lightGallery (src relatifs, ordre de la fiche, pleine259 # taille) ; repli sur les URL absolues du vid canonique (sans /thumbnail/260 # ni couvertures des « propriétés similaires »)261 mc = _CANON_RE.search(html)262 want = mc.group(1) if mc else None263 seen: set = set()264 imgs = []265 for rel in _GALLERY_RE.findall(html):266 if "/thumbnail/" in rel:267 continue268 u = _IMG_HOST + rel269 if u not in seen:270 seen.add(u)271 imgs.append(u)272 if want:273 imgs = [u for u in imgs if f"/{want}/" in u] or imgs274 if not imgs:275 buckets: dict = {}276 for m in _PHOTO_RE.finditer(html):277 _rel, _uid, vid, fname = m.groups()278 u = m.group(0)279 if fname.lower().startswith("thumbnail") or u in seen:280 continue281 seen.add(u)282 buckets.setdefault(vid, []).append(u)283 if want and want in buckets:284 imgs = buckets[want]285 elif buckets:286 imgs = max(buckets.values(), key=len)287 if imgs:288 out["images"] = imgs289290 # specs du tableau « Libellé | Valeur » (texte aplati) : Chambre à coucher,291 # Salle de bain/d'eau, Pièces, Aire habitable (pc/mc), Dimension terrain…292 # (0 et « -- » = non renseigné). Prose « N chambres » gardée en repli.293 text = du.flatten(html)294 mb = (re.search(r"Chambre à coucher\s*\|\s*(\d{1,2})\b", text)295 or re.search(r"(\d{1,2})\s*chambre", text, re.I))296 if mb and int(mb.group(1)) > 0:297 out["bedrooms"] = int(mb.group(1))298 ms = (re.search(r"Salle de bain/d[’']eau\s*\|\s*(\d{1,2})\b", text)299 or re.search(r"(\d{1,2})\s*salle[s]?\s*de\s*bain", text, re.I))300 if ms and int(ms.group(1)) > 0:301 out["bathrooms"] = int(ms.group(1))302 mp2 = re.search(r"Pièces\s*\|\s*(\d{1,2})\b", text)303 if mp2 and int(mp2.group(1)) > 0:304 details.setdefault("Nombre de pièces", int(mp2.group(1)))305 my = re.search(r"Année de construction\s*\|?\s*:?\s*\|?\s*([12]\d{3})\b", text)306 if my:307 out["year_built"] = int(my.group(1))308309 ma = re.search(r"Aire habitable\s*\|\s*([\d\s.,]+?)\s*(pc|pi2|pi²|pi|mc|m2|m²)\b",310 text, re.I)311 if ma:312 v = _num(ma.group(1))313 if v:314 out["area_sqft"] = round(v * (10.7639 if ma.group(2).lower()315 in ("mc", "m2", "m²") else 1), 0)316317 # « Dimension terrain | 26.02x25.29 mc » (LxW) ou superficie directe318 mt = re.search(r"Dimension terrain\s*\|\s*([\d.,]+)\s*[xX]\s*([\d.,]+)"319 r"\s*(pc|pi|mc|m)?\b", text)320 if mt:321 a, b = _num(mt.group(1)), _num(mt.group(2))322 if a and b:323 f = 10.7639 if (mt.group(3) or "").lower() in ("mc", "m") else 1324 out["lot_sqft"] = round(a * b * f, 0)325 else:326 mt2 = re.search(r"Dimension terrain\s*\|\s*([\d\s.,]+?)\s*(pc|mc)\b", text)327 if mt2:328 v = _num(mt2.group(1))329 if v:330 out["lot_sqft"] = round(v * (10.7639 if mt2.group(2).lower() == "mc"331 else 1), 0)332333 mbat = re.search(r"Dimension bâtiment\s*\|\s*([\d][\d\sxX.,]{1,20}?(?:pc|pi|mc|m)?)\s*\|",334 text)335 if mbat:336 details["Dimension bâtiment"] = mbat.group(1).strip()337 for lab in ("Étages", "Garage", "Stationnement privé"):338 mv = re.search(re.escape(lab) + r"\s*\|\s*(\d{1,3})\b", text)339 if mv and int(mv.group(1)) > 0:340 details[lab] = int(mv.group(1))341342 # description HTML de la fiche (le JSON-LD Product la tronque souvent)343 mdsc = re.search(r'class="content-annonce-description-text"[^>]*>(.*?)</div>',344 html, re.S)345 if mdsc:346 d = re.sub(r"\s+", " ",347 _html.unescape(re.sub(r"<[^>]+>", " ", mdsc.group(1)))).strip()348 if len(d) > len(out.get("description") or ""):349 out["description"] = d[:4000]350351 if details:352 out["details"] = details353 return out354355356def _num(s: str) -> float | None:357 try:358 return float(s.replace(" ", "").replace(" ", "").replace(",", "."))359 except (AttributeError, ValueError):360 return None361