Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/logispro_mauricie.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-10-2614#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/logispro_mauricie.py : connecteur LogisPro Mauricie (logispro.ca)91# Trois-Rivières, Cap-de-la-Madeleine, Shawinigan, Bécancour (Gentilly),92# Nicolet, Grandes-Piles. ⚠️ Compagnie DISTINCTE de LogisPro Rimouski93# (logisprorimouski.com, connecteur `logispro`).94# Refonte 2026-10 (thème Elementor « adncommunication ») : l'ancienne page95# /appartements-a-louer/ (cartes div.apartments-item) redirige vers96# /locations/ et le gabarit a entièrement changé. Les logements sont97# désormais des posts CPT « location » exposés par l'API REST98# (/wp-json/wp/v2/location) avec ACF complet (prix, prix promo, adresse99# géocodée + GPS, chambres, salles de bain, superficie, étage, galerie100# d'IDs médias résolus via /wp-json/wp/v2/media) et taxonomies101# (disponibilité, ville/secteur, dimension, caractéristiques,102# stationnement, proximité). Le site publie tout l'inventaire à louer103# (dispo immédiate ET à venir) — d'où un volume bien plus grand qu'avant104# la refonte (~69 vs ~12).105# Granularité : une annonce par logement.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import html as htmllib110import re111112from ..schema import Listing, normalize_unit_type113from .base import BaseConnector114115BASE = "https://logispro.ca"116API = f"{BASE}/wp-json/wp/v2"117118_ETAGES = {119 "rez-de-chaussee": "Rez-de-chaussée",120 "1er-etage": "1er étage",121 "2e-etage": "2e étage",122 "3e-etage": "3e étage",123}124125126def _clean(txt: str) -> str:127 txt = re.sub(r"<[^>]+>", " ", txt or "")128 return re.sub(r"\s+", " ", htmllib.unescape(txt)).strip()129130131class LogisProMauricieConnector(BaseConnector):132 source_id = "logispro_mauricie"133 request_delay = 0.7134 max_pages = 5 # garde-fou (5 x 100 posts)135 max_media_ids = 25 # images max par annonce136137 # -- helpers REST ----------------------------------------------------------138 def _terms(self, taxonomy: str) -> dict[int, str]:139 try:140 data = self.get(141 f"{API}/{taxonomy}?per_page=100&_fields=id,name").json()142 return {t["id"]: htmllib.unescape(t["name"]) for t in data}143 except Exception:144 return {}145146 def _media_urls(self, ids: list) -> list[str]:147 """IDs de médias -> URLs. Lève en cas d'échec HTTP : ne JAMAIS mettre148 en cache une galerie vide sur un hoquet (poison du detail_cache)."""149 ids = [str(i) for i in ids if str(i).isdigit()][: self.max_media_ids]150 if not ids:151 return []152 url = (f"{API}/media?include={','.join(ids)}"153 f"&per_page=100&_fields=id,source_url")154 data = self.get(url).json()155 by_id = {str(m["id"]): m.get("source_url", "") for m in data}156 return [by_id[i] for i in ids if by_id.get(i)]157158 # -- fetch ------------------------------------------------------------------159 def fetch(self) -> list[Listing]:160 dispos = self._terms("location_disponibilite")161 villes = self._terms("location_ville")162 dims = self._terms("location_dimension")163 caracs = self._terms("location_caracteristique")164 stationnements = self._terms("location_stationnement")165 proximites = self._terms("location_proximite")166167 posts: list[dict] = []168 for page in range(1, self.max_pages + 1):169 try:170 batch = self.get(171 f"{API}/location?per_page=100&page={page}").json()172 except Exception:173 if page == 1:174 raise # erreur transitoire ≠ liste vide (évite les faux 0)175 break # fin de pagination (WP renvoie 400 au-delà)176 if not isinstance(batch, list) or not batch:177 break178 posts.extend(batch)179 if len(batch) < 100:180 break181182 listings: list[Listing] = []183 for p in posts:184 try:185 lst = self._parse_location(p, dispos, villes, dims, caracs,186 stationnements, proximites)187 except Exception:188 continue189 if lst:190 listings.append(lst)191 # posts publiés mais zéro parsé = format REST/ACF changé, pas un vrai zéro192 if posts and not listings:193 raise RuntimeError(194 f"{len(posts)} posts « location » REST mais 0 annonce parsée "195 "— structure ACF/taxonomies changée ?")196 return listings197198 def _parse_location(self, p: dict, dispos: dict, villes: dict,199 dims: dict, caracs: dict, stationnements: dict,200 proximites: dict) -> Listing | None:201 acf = p.get("acf") or {}202 slug = (p.get("slug") or "").strip()203 if not slug or p.get("status") not in (None, "publish"):204 return None205206 title = _clean((p.get("title") or {}).get("rendered") or "")207208 # Adresse géocodée ACF : « 6105#3, rue de la Mattawin, Trois-Rivières,209 # QC G8Y 0K6 » + ville propre + GPS210 carte = acf.get("carte") or {}211 city = (carte.get("city") or "").strip()212 address = (carte.get("address") or "").replace(", Canada", "").strip()213 if not address:214 address = ", ".join(s for s in (215 str(acf.get("adresse") or "").strip(), city) if s)216 lat = lng = None217 try:218 lat, lng = float(carte["lat"]), float(carte["lng"])219 except (KeyError, TypeError, ValueError):220 lat = lng = None221222 # Secteur = terme « ville » quand il diffère de la ville géocodée223 # (Parc Isabeau, Vieilles-Forges–Saint-Jean, Gentilly, Cap-de-la-M…)224 ville_term = next((villes[i] for i in (p.get("location_ville") or [])225 if i in villes), "")226 sector = ville_term if ville_term and ville_term != city else ""227228 # Prix (ACF numérique) + prix promo éventuel (le plus bas affiché)229 price = None230 price_label = ""231 try:232 price = float(acf.get("prix") or 0) or None233 except (TypeError, ValueError):234 price = None235 if price is not None:236 price_label = f"{price:.0f} $ / mois"237 promo = None238 try:239 promo = float(acf.get("prix_promo") or 0) or None240 except (TypeError, ValueError):241 promo = None242 if promo and (price is None or promo < price):243 price_label = (f"{promo:.0f} $ / mois (promo"244 + (f", prix régulier {price:.0f} $" if price else "")245 + ")")246 price = promo247 if price is not None and not (100 <= price <= 20000):248 price = None249250 # Disponibilité (taxonomie : « Immédiatement », « 1er novembre », …)251 dispo = next((dispos[i] for i in (p.get("location_disponibilite") or [])252 if i in dispos), "")253 if dispo.lower() == "immédiatement":254 availability = "Disponible immédiatement"255 elif dispo:256 availability = f"Disponible le {dispo}"257 else:258 availability = ""259260 unit_type = normalize_unit_type(261 next((dims[i] for i in (p.get("location_dimension") or [])262 if i in dims), ""))263264 bedrooms = bathrooms = None265 try:266 bedrooms = float(acf["nb_chambres"]) or None267 except (KeyError, TypeError, ValueError):268 pass269 try:270 bathrooms = float(acf["nb_salles_bain"]) or None271 except (KeyError, TypeError, ValueError):272 pass273274 area_sqft = None275 try:276 val = float(acf.get("superficie") or 0)277 if 80 <= val <= 20000:278 area_sqft = val279 except (TypeError, ValueError):280 pass281282 amenities = [caracs[i] for i in (p.get("location_caracteristique") or [])283 if i in caracs]284 amenities += [stationnements[i]285 for i in (p.get("location_stationnement") or [])286 if i in stationnements]287 etage = str(acf.get("etage") or "").strip()288 if etage:289 amenities.append(290 "Étage : " + _ETAGES.get(etage, etage.replace("-", " ")))291 prix_note = str(acf.get("prix_note") or "").strip()292 if prix_note:293 amenities.append(prix_note)294295 details: dict = {}296 prox = [proximites[i] for i in (p.get("location_proximite") or [])297 if i in proximites]298 if prox:299 details["proximite"] = prox300301 description = _clean((p.get("content") or {}).get("rendered") or "")[:1200]302303 # Galerie : IDs de médias -> URLs, avec cache BD invalidé par la date304 # de modification du post (toute retouche de la fiche la rafraîchit).305 images: list[str] = []306 gallery_ids = acf.get("galerie") or []307 key = f"v1:{p.get('modified', '')}:{len(gallery_ids)}"308 try:309 payload = self.detail(310 slug, key,311 lambda ids=gallery_ids: {"images": self._media_urls(ids)})312 images = payload.get("images") or []313 except Exception:314 images = [] # hoquet média : annonce conservée, photos au prochain sync315316 return Listing(317 source=self.source_id,318 external_id=slug,319 url=p.get("link") or f"{BASE}/location/{slug}/",320 title=title or address or slug,321 address=address,322 sector=sector,323 city=city,324 unit_type=unit_type,325 bedrooms=bedrooms,326 bathrooms=bathrooms,327 price=price,328 price_label=price_label,329 availability=availability,330 area_sqft=area_sqft,331 description=description,332 amenities=amenities[:25],333 details=details,334 images=images,335 lat=lat,336 lng=lng,337 )338