Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/multi_logis.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-08-0914#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/multi_logis.py : connecteur Multi-Logis (multi-logis.com — 500+91# logements : Sept-Îles, Port-Cartier — plus gros parc de la Côte-Nord —92# et aussi Lévis, toutes les villes conservées). WordPress + Elementor +93# JetEngine + plugin maison « multilogis-listing », tout rendu serveur.94# Liste /trouver-mon-appartement/ : une carte par bâtiment (nom, adresse,95# typologies offertes, « À partir de »). Page /batiment/<slug>/ (via cache96# BD) : unités disponibles individuelles (numéro, type, description, loyer,97# superficie, disponibilité, galerie, plan), adresse structurée du champ ACF98# (ville, code postal, lat/lng) et listes « Inclus » / « Caractéristiques »99# de l'immeuble. Une annonce Lou-Ka = une unité disponible. Les champs des100# unités sont identifiés par leur CONTENU (motifs « $/mois », « Studio/n½ »,101# « Superficie: », « Disponibilité: ») — robustes aux ids Elementor.102# Immeubles commerciaux (« Le St-Georges ») sans unités : ignorés d'eux-mêmes.103# robots.txt ouvert, sitemap Yoast.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import hashlib108import re109110from bs4 import BeautifulSoup111112from ..schema import Listing, normalize_unit_type, parse_price113from .base import BaseConnector114115BASE = "https://multi-logis.com"116LIST_URL = f"{BASE}/trouver-mon-appartement/"117118# suffixe de redimensionnement WordPress (« -1024x1024.png » -> pleine taille)119_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)120121_TYPE_RE = re.compile(r"^(studio|\d\s*½|\d\s*1/2)$", re.I)122_ACF_RE = re.compile(r"'(address|city|post_code|lat|lng)'\s*=>\s*'?([^',\n]+)'?")123124125def _clean_img(url: str) -> str:126 return _SIZE_SUFFIX.sub("", url.strip())127128129class MultiLogisConnector(BaseConnector):130 source_id = "multi_logis"131 request_delay = 0.6132 max_details = 25 # garde-fou pages bâtiment (vraies requêtes par sync)133134 def fetch(self) -> list[Listing]:135 html = self.get(LIST_URL).text136 soup = BeautifulSoup(html, "html.parser")137138 # cartes bâtiment (le sélecteur de carte duplique la grille : dédupliquer)139 buildings: dict[str, dict] = {}140 for item in soup.select(".jet-listing-grid__item"):141 link = item.select_one('a[href*="/batiment/"]')142 if not link:143 continue144 m = re.search(r"/batiment/([^/?#]+)", link["href"])145 if not m:146 continue147 slug = m.group(1).strip("/")148 fields = [re.sub(r"\s+", " ", f.get_text(" ", strip=True))149 for f in item.select(".jet-listing-dynamic-field__content")]150 fields = [f for f in fields if f]151 if slug in buildings and len(fields) <= len(buildings[slug]["fields"]):152 continue153 buildings[slug] = {"fields": fields}154155 self._fetched = 0156 listings: list[Listing] = []157 for slug, info in buildings.items():158 try:159 listings.extend(self._parse_building(slug, info["fields"]))160 except Exception:161 continue162 return listings163164 # -- un bâtiment ------------------------------------------------------------------165 def _parse_building(self, slug: str, fields: list[str]) -> list[Listing]:166 url = f"{BASE}/batiment/{slug}/"167 name = fields[0] if fields else slug168 card_addr = next((f for f in fields if re.search(r",\s*QC", f, re.I)), "")169170 # page bâtiment (cache BD, invalidée quand la carte liste change)171 key = hashlib.sha1("|".join(fields).encode("utf-8")).hexdigest()172173 def fetch_fn():174 if self._fetched >= self.max_details:175 raise RuntimeError("budget de pages bâtiment atteint")176 self._fetched += 1177 return self._fetch_building(url)178179 payload = self.detail(slug, key, fetch_fn)180 if not payload:181 return []182183 address = payload.get("address") or card_addr184 city = payload.get("city") or ""185 if payload.get("post_code") and payload["post_code"] not in address:186 address = f"{address}, {payload['post_code']}"187 lat, lng = payload.get("lat"), payload.get("lng")188 amenities_building = payload.get("amenities", [])189190 out: list[Listing] = []191 for u in payload.get("units", []):192 numero = u.get("numero") or ""193 m = re.search(r"#\s*([\w-]+)", numero)194 unit_no = (m.group(1) if m else "").strip(" ,#").lower()195 if not unit_no:196 # unité affichée sans numéro (« Appartement # ») : identifiant197 # stable dérivé du contenu invariant (type, superficie, plan,198 # début de description) — pas du prix ni de la disponibilité199 sig = (f"{u.get('type', '')}|{u.get('superficie', '')}|"200 f"{u.get('plan', '')}|{u.get('description', '')[:40]}")201 unit_no = "sn-" + hashlib.sha1(sig.encode("utf-8")).hexdigest()[:8]202203 amenities = list(amenities_building)204 details: dict = {"building": name}205 if u.get("plan"):206 details["floorplan"] = u["plan"]207208 area = None209 if u.get("superficie"):210 m_a = re.search(r"([\d\s]{2,6})\s*pi", u["superficie"])211 if m_a:212 val = float(re.sub(r"\s", "", m_a.group(1)))213 if 80 <= val <= 20000:214 area = val215216 availability = ""217 if u.get("disponibilite"):218 availability = re.sub(r"^Disponibilit[ée]\s*:\s*", "",219 u["disponibilite"], flags=re.I).strip()220221 out.append(Listing(222 source=self.source_id,223 external_id=f"{slug}--{unit_no}",224 url=url,225 title=f"{name} — {numero}" if numero else name,226 address=address,227 city=city,228 unit_type=normalize_unit_type(u.get("type", "")),229 price=parse_price(u.get("loyer", "")),230 price_label=u.get("loyer", ""),231 availability=availability,232 area_sqft=area,233 description=u.get("description", ""),234 amenities=amenities,235 details=details,236 images=(u.get("images") or [])[:20],237 lat=lat,238 lng=lng,239 ))240 return out241242 # -- page bâtiment ------------------------------------------------------------------243 def _fetch_building(self, url: str) -> dict:244 """Payload JSON-sérialisable : unités disponibles + infos du bâtiment."""245 resp = self.get(url)246 html = resp.text247 soup = BeautifulSoup(html, "html.parser")248 payload: dict = {}249250 # adresse structurée : champ ACF Google Maps rendu en clair dans la page251 # ('address' => '40, rue Saint-Étienne, à Lévis', 'city' => 'Lévis'…)252 acf = dict()253 for k, v in _ACF_RE.findall(html):254 acf.setdefault(k, v.strip())255 if acf.get("address"):256 payload["address"] = re.sub(r",?\s*à\s+", ", ", acf["address"])257 for k in ("city", "post_code"):258 if acf.get(k):259 payload[k] = acf[k]260 try:261 payload["lat"] = float(acf["lat"])262 payload["lng"] = float(acf["lng"])263 except (KeyError, ValueError):264 pass265266 # listes « Inclus » et « Caractéristiques » de l'immeuble267 amenities: list[str] = []268 for h in soup.find_all(["h2", "h3", "h4"]):269 titre = h.get_text(strip=True).lower()270 if titre not in ("inclus", "caractéristiques", "caracteristiques"):271 continue272 cont = h.find_parent(class_="elementor-widget")273 for sib in (cont.find_next_siblings() if cont else []):274 lis = sib.select("li")275 if lis:276 for li in lis:277 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))278 if t and t not in amenities:279 amenities.append(t)280 break281 payload["amenities"] = amenities[:25]282283 # unités disponibles : items JetEngine contenant un champ « numéro »284 units: list[dict] = []285 for item in soup.select(".jet-listing-grid__item"):286 unit = self._parse_unit(item)287 if unit:288 units.append(unit)289 payload["units"] = units290 return payload291292 # -- une unité (classification des champs par contenu) -------------------------------293 def _parse_unit(self, item) -> dict | None:294 texts: list[str] = []295 for f in item.select(".jet-listing-dynamic-field__content"):296 t = re.sub(r"\s+", " ", f.get_text(" ", strip=True))297 if t:298 texts.append(t)299 unit: dict = {}300 for t in texts:301 if re.search(r"^Appartement\s*#", t, re.I) and "numero" not in unit:302 unit["numero"] = t.rstrip(" ,")303 elif _TYPE_RE.match(t) and "type" not in unit:304 unit["type"] = t305 elif re.search(r"\$\s*/\s*mois|\d\$/mois", t) and "loyer" not in unit:306 unit["loyer"] = t307 elif re.search(r"^Superficie\s*:", t, re.I):308 unit["superficie"] = t309 elif re.search(r"^Disponibilit[ée]\s*:", t, re.I):310 unit["disponibilite"] = t311 elif len(t) > 60 and "description" not in unit:312 unit["description"] = t[:1200]313 if "numero" not in unit:314 return None # carte bâtiment / bloc décoratif315316 # galerie de l'unité (liens lightbox pleine taille)317 images: list[str] = []318 gal = item.select_one(".single-unit-gallery") or item319 for a in gal.select('a[href*="/wp-content/uploads/"]'):320 u = _clean_img(a["href"])321 if u.startswith("http") and u not in images:322 images.append(u)323 unit["images"] = images324325 # plan d'étage (« Voir le plan », seulement si un lien réel est fourni)326 for a in item.select("a[href]"):327 if "plan" in a.get_text(strip=True).lower():328 href = a["href"].strip()329 if href.startswith("http") and "/wp-content/" in href:330 unit["plan"] = href331 break332 return unit333