Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/dynamic.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/dynamic.py : connecteur Gestion immobilière Dynamic91# (lesgestionsdynamic.com) — apparts à Sherbrooke, Magog, Granby, East Angus.92# WordPress + thème immobilier Houzez, même famille que gimcote.py : archive93# /a-louer/ paginée (cartes div.item-listing-wrap avec prix, galerie94# data-images, data-listid). Particularité locale : pas d'adresse ni de95# statut sur la carte — la disponibilité est un suffixe du titre96# (« IMMÉDIATEMENT », « JUILLET », « 1er AOÛT »…) et l'adresse/ville/GPS97# viennent de la fiche détail (bloc #property-address-wrap, carte Houzez).98# Sert de CLASSE DE BASE à la famille Houzez de l'Estrie : Gestimmo Estrie99# (gestimmo_estrie.py) et Agence de location Sherbrooke / groupe Prestiplex100# (agence_sherbrooke.py) n'en redéfinissent que les constantes et les101# crochets carte (statut/étiquette/adresse).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import html as htmllib107import json108import re109110from bs4 import BeautifulSoup111112from ..schema import (Listing, normalize_unit_type, parse_price,113 strip_accents)114from .base import BaseConnector115116# variantes redimensionnées WordPress (-584x438.jpg) -> pleine taille117_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)118_MAP_LATLNG_RE = re.compile(119 r'"lat"\s*:\s*"?(-?\d+\.\d+)"?\s*,\s*"lng"\s*:\s*"?(-?\d+\.\d+)"?')120121# villes réelles desservies par la famille (jamais devinées : on ne retient la122# ville que si elle apparaît telle quelle dans l'adresse ou le bloc « Ville »)123_KNOWN_CITIES = [124 "Sherbrooke", "Magog", "Granby", "East Angus", "Orford", "Waterville",125 "Windsor", "Coaticook", "Ascot Corner", "Lennoxville", "Richmond",126 "Cookshire-Eaton", "Bromptonville", "Cowansville", "Bromont", "Valcourt",127]128129# suffixe de disponibilité dans les titres Dynamic : « IMMÉDIATEMENT »,130# « JUILLET », « 1er AOÛT », « LOUÉ »…131_AVAIL_TITLE_RE = re.compile(132 r"(imm[eé]diatement|d[èe]s maintenant|lou[ée]|"133 r"(?:1er\s+|15\s+)?(?:janvier|f[ée]vrier|mars|avril|mai|juin|juillet|"134 r"ao[ûu]t|septembre|octobre|novembre|d[ée]cembre)(?:\s+20\d\d)?)\s*$",135 re.I)136137138def _clean_price_label(label: str) -> str:139 """'1,450$/mois' ou '1 450 $/mois' -> compatible parse_price."""140 return re.sub(r"(\d)[,\s](\d{3})", r"\1\2", label)141142143def _city_from_parts(parts: list[str]) -> tuple[str, str]:144 """(ville, secteur) depuis les segments Nominatim de address.item-address :145 « 89, Rue des Pins, East Angus, Le Haut-Saint-François, … » — la ville est146 le segment qui correspond à une ville connue, le secteur le segment qui la147 précède (micro-quartier) quand il ne fait pas partie de l'adresse civique."""148 for i, p in enumerate(parts):149 for city in _KNOWN_CITIES:150 if strip_accents(p.strip().lower()) == strip_accents(city.lower()):151 sector = ""152 if i >= 3: # [n° civique, rue, quartier, ville, ...]153 sector = parts[i - 1].strip()154 return city, sector155 return "", ""156157158class DynamicConnector(BaseConnector):159 source_id = "dynamic"160 request_delay = 0.6161 max_pages = 12 # garde-fou de pagination162 max_details = 80 # garde-fou fiches détail (vraies requêtes)163164 BASE = "https://lesgestionsdynamic.com"165 LIST_PATH = "/a-louer/"166 CITY_DEFAULT = "Sherbrooke" # repli si la fiche ne précise pas la ville167168 def fetch(self) -> list[Listing]:169 listings: dict[str, Listing] = {}170 for page in range(1, self.max_pages + 1):171 url = (f"{self.BASE}{self.LIST_PATH}" if page == 1172 else f"{self.BASE}{self.LIST_PATH}page/{page}/")173 try:174 html = self.get(url).text175 except Exception:176 break177 soup = BeautifulSoup(html, "html.parser")178 cards = soup.select("div.item-listing-wrap")179 if not cards:180 break181 for card in cards:182 try:183 self._parse_card(card, listings)184 except Exception:185 continue186187 # fiches détail (cache BD) : adresse/ville/GPS, description,188 # caractéristiques, type d'unité (aperçu Houzez), galerie complète189 self._fetched = 0190 for lst in listings.values():191 card_key = hashlib.sha1(192 f"{lst.title}|{lst.price_label}|{lst.availability}"193 .encode("utf-8")).hexdigest()194 try:195 payload = self.detail(lst.external_id, card_key,196 lambda u=lst.url: self._fetch_detail(u))197 except Exception:198 continue199 self._apply_detail(lst, payload)200 return list(listings.values())201202 # -- crochets par site --------------------------------------------------------203 def _card_availability(self, card, title: str) -> str:204 """Dynamic : la disponibilité est un suffixe du titre de l'annonce."""205 m = _AVAIL_TITLE_RE.search(title)206 return m.group(1).strip() if m else ""207208 # -- carte Houzez ---------------------------------------------------------------209 def _parse_card(self, card, listings: dict[str, Listing]) -> None:210 link = card.select_one("h2.item-title a[href]")211 if not link:212 return213 url = link["href"]214 title = re.sub(r"\s+", " ", link.get_text(" ", strip=True)).strip()215 m = re.search(r"/(?:property|appartement)/([^/]+)/?", url)216 slug = m.group(1) if m else ""217 listid_el = card.select_one("[data-listid]")218 ext_id = (listid_el.get("data-listid") if listid_el else "") or slug219 if not ext_id or str(ext_id) in listings:220 return221222 # exclusions : logements loués + espaces non résidentiels223 if re.search(r"\blou[ée]s?\b", title, re.I):224 return225 if re.search(r"stationnement|commercial|rangement|garage|entrep[oô]t",226 title, re.I):227 return228 availability = self._card_availability(card, title)229 if re.search(r"lou[ée]", availability, re.I):230 return231232 price_el = card.select_one("li.item-price")233 price_label = price_el.get_text(" ", strip=True) if price_el else ""234235 # adresse Nominatim de la carte (présente chez Agence, absente chez236 # Dynamic/Gestimmo — la fiche détail prendra le relais)237 address = sector = ""238 city = self.CITY_DEFAULT239 addr_el = card.select_one("address.item-address")240 if addr_el:241 full = addr_el.get_text(" ", strip=True)242 parts = [p.strip() for p in full.split(",") if p.strip()]243 address = ", ".join(parts[:2]) if len(parts) >= 2 else full244 c, s = _city_from_parts(parts)245 if c:246 city, sector = c, s247248 # commodités des cartes Houzez : chambres / salles de bain / pi²249 amenities: list[str] = []250 for li in card.select("ul.item-amenities li"):251 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))252 t = t.replace("Beds:", "Chambres :").replace("Bath:", "Salle(s) de bain :")253 if t and t not in amenities:254 amenities.append(t)255256 # galerie : attribut data-images (JSON, URLs redimensionnées)257 images: list[str] = []258 raw = card.get("data-images") or ""259 if raw:260 try:261 urls = json.loads(htmllib.unescape(raw))262 except Exception:263 urls = re.findall(r"https?:[^\"',\\]+", htmllib.unescape(raw))264 for u in urls:265 if isinstance(u, dict): # variante Houzez : objets {url: …}266 u = u.get("url") or u.get("src") or u.get("image") or ""267 if not isinstance(u, str):268 continue269 u = u.replace("\\/", "/").strip()270 if u.startswith("http"):271 u = _SIZE_SUFFIX.sub("", u)272 if u not in images:273 images.append(u)274 if not images:275 thumb = card.select_one("img.wp-post-image[src]")276 if thumb:277 images = [_SIZE_SUFFIX.sub("", thumb["src"])]278279 # type d'unité depuis le titre, seulement si le motif est net280 # (normalize_unit_type retourne le texte brut quand rien ne matche)281 unit_type = normalize_unit_type(title)282 if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",283 unit_type or ""):284 unit_type = ""285286 listings[str(ext_id)] = Listing(287 source=self.source_id,288 external_id=str(ext_id),289 url=url,290 title=title,291 address=address,292 sector=sector,293 city=city,294 unit_type=unit_type,295 price=parse_price(_clean_price_label(price_label)),296 price_label=price_label,297 availability=availability,298 amenities=amenities,299 images=images[:30],300 )301302 # -- fiche détail (Houzez) -----------------------------------------------------303 def _fetch_detail(self, url: str) -> dict:304 """Adresse structurée (#property-address-wrap), description,305 caractéristiques, type d'unité (aperçu) et GPS (carte Houzez)."""306 if self._fetched >= self.max_details:307 raise RuntimeError("budget de fiches détail atteint")308 self._fetched += 1309 html = self.get(url).text310 soup = BeautifulSoup(html, "html.parser")311 out: dict = {}312313 desc_el = soup.select_one("#property-description-wrap")314 if desc_el:315 txt = desc_el.get_text("\n", strip=True)316 txt = re.sub(r"^Description\n", "", txt)317 out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]318319 out["amenities"] = [a.get_text(" ", strip=True)320 for a in soup.select("#property-features-wrap li")321 if a.get_text(strip=True)][:25]322323 # bloc adresse : « Adresse | 375 rue terrill | Ville |324 # Fleurimont (Sherbrooke) | Code postal | J1E 3S7 »325 for li in soup.select("#property-address-wrap li"):326 st, sp = li.find("strong"), li.find("span")327 if not (st and sp):328 continue329 lab = strip_accents(st.get_text(" ", strip=True).lower())330 val = sp.get_text(" ", strip=True)331 if lab.startswith("adresse"):332 out["address"] = val333 elif lab.startswith("ville"):334 out["city_raw"] = val335 elif "postal" in lab:336 out["postal"] = val337338 # adresse Nominatim complète (repli ville/secteur)339 addr_el = soup.select_one("address.item-address")340 if addr_el:341 out["item_address"] = addr_el.get_text(" ", strip=True)342343 # type d'unité : aperçu Houzez (« Appartement 4 1/2 ») — exiger un344 # motif net (« … 4 1/2 », « Studio »…), jamais le mot « chambres » du345 # compteur de pièces346 ov = soup.select_one(".property-overview-wrap, #property-overview-wrap")347 if ov:348 m = re.search(r"(\d\s*(?:1/2|½)|\bstudio\b|\bloft\b|\bmaison\b)",349 ov.get_text(" ", strip=True), re.I)350 if m:351 out["type_raw"] = m.group(1)352353 m = _MAP_LATLNG_RE.search(html)354 if m:355 out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))356 return out357358 def _apply_detail(self, lst: Listing, d: dict) -> None:359 """Reporte le payload (frais ou cache BD) sur l'annonce."""360 if not d:361 return362 if d.get("description"):363 lst.description = d["description"]364 if d.get("amenities"):365 lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))366367 # adresse structurée de la fiche ; « Ville » au format368 # « Fleurimont (Sherbrooke) » (secteur (ville)) ou « Magog »369 if d.get("address") and not lst.address:370 lst.address = d["address"]371 city_raw = (d.get("city_raw") or "").strip()372 if city_raw:373 m = re.match(r"^(.*?)\s*\((.+)\)\s*$", city_raw)374 inner = (m.group(2).strip() if m else city_raw)375 outer = (m.group(1).strip() if m else "")376 c, _ = _city_from_parts([inner])377 if c: # « Fleurimont (Sherbrooke) »378 lst.city = c379 if outer and not lst.sector:380 lst.sector = outer381 else:382 c2, _ = _city_from_parts([city_raw])383 if c2: # « Magog »384 lst.city = c2385 elif not lst.sector: # « Nord », « Centre-ville »…386 lst.sector = city_raw387 elif d.get("item_address"):388 parts = [p.strip() for p in d["item_address"].split(",") if p.strip()]389 c, s = _city_from_parts(parts)390 if c:391 lst.city = c392 if s and not lst.sector:393 lst.sector = s394 if not lst.address and d.get("item_address"):395 parts = [p.strip() for p in d["item_address"].split(",") if p.strip()]396 if len(parts) >= 2:397 lst.address = ", ".join(parts[:2])398399 if not lst.unit_type and d.get("type_raw"):400 lst.unit_type = normalize_unit_type(d["type_raw"])401 if d.get("lat") is not None and d.get("lng") is not None:402 lst.lat, lst.lng = d["lat"], d["lng"]403