Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/simard.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0814#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/simard.py : connecteur Immeubles Simard (immeublessimard.com)91# Section « À louer » — catégorie appartement uniquement (les bureaux,92# commerces et laboratoires sont exclus d'office). Pages détail (cache BD93# self.detail) : bloc specs étiqueté (#infos : pièces, prix, superficie,94# disponibilité), « Caractéristiques et inclusions », description, images.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import hashlib99import re100101from bs4 import BeautifulSoup102103from ..schema import (Listing, infer_city, merge_details, normalize_unit_type,104 strip_accents)105from .base import BaseConnector106107BASE = "https://immeublessimard.com"108LIST_URL = f"{BASE}/a-louer/categorie/appartement/"109110DETAIL_RE = re.compile(r"/a-louer/appartement/([a-z0-9\-]+)/([a-z0-9\-]+)/?$")111IMG_RE = re.compile(112 r"https://immeublessimard\.com/wp-content/uploads/[^\"'\\\s\)]+"113 r"\.(?:jpg|jpeg|png|webp)", re.I)114IMG_NOISE_RE = re.compile(r"logo|favicon|icon", re.I)115# Prix affiché « $1975.00 » ou « 1 975$ »116PRICE_RE = re.compile(r"(?:\$\s*([\d\s,]+(?:\.\d{2})?)|([\d][\d\s]*(?:,\d{2})?)\s*\$)")117118119def _parse_price(text: str) -> float | None:120 """Gère les deux formats : « $1975.00 » et « 1 975$ »."""121 if not text:122 return None123 s = text.replace(" ", " ").replace(" ", " ")124 s = re.sub(r"(\d),(\d{3})", r"\1\2", s) # 1,975 -> 1975125 m = PRICE_RE.search(s)126 if not m:127 return None128 num = (m.group(1) or m.group(2)).replace(" ", "").replace(",", ".")129 try:130 val = float(num)131 except ValueError:132 return None133 return val if 100 <= val <= 20000 else None134135136class SimardConnector(BaseConnector):137 source_id = "simard"138 request_delay = 0.6139 max_details = 60 # garde-fou140141 def fetch(self) -> list[Listing]:142 html = self.get(LIST_URL).text143 soup = BeautifulSoup(html, "html.parser")144145 listings: dict[str, Listing] = {}146 for card in soup.select("div.item a[href*='/a-louer/appartement/']"):147 try:148 lst = self._parse_card(card)149 except Exception:150 continue151 if lst and lst.external_id not in listings:152 listings[lst.external_id] = lst153154 # Pages détail (cache BD) : specs, prix, dispo, commodités, images155 fetched = 0156 for i, lst in enumerate(listings.values()):157 if i >= self.max_details:158 break159 # « v3 » : version du format de payload (invalide les caches anciens)160 key = hashlib.sha1(161 f"v3|{lst.title}|{lst.description}".encode("utf-8")).hexdigest()162163 def _fetch(url=lst.url):164 nonlocal fetched165 if fetched >= self.max_details:166 raise RuntimeError("plafond de requêtes détail atteint")167 fetched += 1168 return self._fetch_detail(url)169170 try:171 payload = self.detail(lst.external_id, key, _fetch)172 except Exception:173 payload = {}174 if payload:175 self._apply_detail(lst, payload)176177 return list(listings.values())178179 def _parse_card(self, card) -> Listing | None:180 href = card.get("href", "").split("?")[0]181 m = DETAIL_RE.search(href)182 if not m:183 return None184 sector_slug, slug = m.groups()185 title_el = card.select_one("h2")186 sector_el = card.select_one(".secteur")187 bullets = [li.get_text(" ", strip=True) for li in card.select("li")]188 title = title_el.get_text(" ", strip=True) if title_el else slug189 sector = sector_el.get_text(strip=True) if sector_el else \190 sector_slug.replace("-", " ").title()191 unit_type = ""192 for b in bullets + [title]:193 m2 = re.search(r"\d\s*(?:½|1/2)|studio|loft", b, re.I)194 if m2:195 unit_type = normalize_unit_type(m2.group(0))196 break197 # certains titres SONT l'adresse civique (« 1276-24 Chanoine-Morel »)198 address = title if re.match(r"^\d{2,5}(?:-\d+[A-Za-z]?)?\s+\D", title) else ""199 return Listing(200 source=self.source_id,201 external_id=slug,202 url=href if href.startswith("http") else BASE + href,203 title=title,204 address=address,205 sector=sector,206 city=infer_city(sector),207 unit_type=unit_type,208 description=" • ".join(b for b in bullets if b)[:400],209 )210211 def _fetch_detail(self, url: str) -> dict:212 """Télécharge une fiche et en extrait le payload brut (cacheable)."""213 html = self.get(url).text214 soup = BeautifulSoup(html, "html.parser")215216 # Bloc specs étiqueté (#infos) : « Nombre de pièces : 4½ »,217 # « Prix : $1975 », « Superficie : 902 pi2 », « Disponibilité : … »218 specs: dict[str, str] = {}219 for li in soup.select("#infos ul li"):220 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))221 m = re.match(r"(Nombre de pièces|Prix|Superficie|Disponibilité)"222 r"\s*:\s*(.+)", t, re.I)223 if m:224 specs[strip_accents(m.group(1).lower())] = m.group(2).strip()225226 # statut affiché dans l'entête (« Disponible », « Loué »)227 status_el = soup.select_one("#infos p.details .text-right")228 status = status_el.get_text(" ", strip=True) if status_el else ""229230 # bloc « Location : » — contact structuré (tel:/mailto:)231 contact: dict = {}232 tel = soup.select_one("#infos a[href^='tel:']")233 if tel:234 digits = re.sub(r"\D", "", tel.get("href", ""))235 if len(digits) == 10:236 contact["phone"] = f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"237 mail = soup.select_one("#infos a[href^='mailto:']")238 if mail:239 m = re.match(r"mailto:([^?]+)", mail.get("href", ""))240 if m:241 contact["email"] = m.group(1).strip()242243 # « Caractéristiques et inclusions » + « Description »244 amenities: list[str] = []245 desc_parts: list[str] = []246 contenu = soup.select_one("section .contenu")247 if contenu:248 for h2 in contenu.select("h2"):249 title = h2.get_text(" ", strip=True)250 if re.search(r"Caractéristiques", title, re.I):251 ul = h2.find_next_sibling("ul")252 for li in (ul.select("li") if ul else []):253 t = li.get_text(" ", strip=True)254 if t and len(t) < 80 and t not in amenities:255 amenities.append(t)256 elif re.search(r"Description", title, re.I):257 for p in h2.find_next_siblings("p"):258 t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))259 if t:260 desc_parts.append(t)261 desc = " ".join(desc_parts)262 if not desc: # repli : meta description263 og = soup.find("meta", attrs={"property": "og:description"}) or \264 soup.find("meta", attrs={"name": "description"})265 desc = (og.get("content") or "").strip() if og else ""266267 imgs = [u for u in dict.fromkeys(IMG_RE.findall(html))268 if not IMG_NOISE_RE.search(u)]269 # éliminer les variantes redimensionnées quand l'originale est là270 originals = {re.sub(r"-\d+x\d+(\.\w+)$", r"\1", u) for u in imgs}271 images = [u for u in imgs272 if re.sub(r"-\d+x\d+(\.\w+)$", r"\1", u) == u273 or re.sub(r"-\d+x\d+(\.\w+)$", r"\1", u) not in originals][:25]274275 return {"specs": specs, "status": status, "amenities": amenities,276 "contact": contact, "description": desc[:1200],277 "images": images}278279 def _apply_detail(self, lst: Listing, payload: dict) -> None:280 """Applique le payload d'une fiche (frais ou depuis le cache BD)."""281 specs = payload.get("specs") or {}282283 if specs.get("prix"):284 price = _parse_price(specs["prix"])285 if price:286 lst.price = price287 lst.price_label = specs["prix"]288 if lst.price is None:289 # repli : prix dans la description (« Prix: $1975.00 … ») en290 # ignorant les mentions de stationnement (« Stationnement; $90.00 »)291 cleaned = re.sub(r"[Ss]tationnement[^.]{0,40}\$\s*[\d.,]+", " ",292 payload.get("description") or "")293 price = _parse_price(cleaned)294 if price:295 lst.price = price296 m = PRICE_RE.search(re.sub(r"(\d),(\d{3})", r"\1\2", cleaned))297 lst.price_label = m.group(0).strip() if m else ""298299 if specs.get("disponibilite"):300 lst.availability = f"Disponibilité : {specs['disponibilite']}"301 elif payload.get("status") and re.search(r"disponible",302 payload["status"], re.I):303 lst.availability = payload["status"]304305 if specs.get("nombre de pieces"):306 lst.unit_type = normalize_unit_type(specs["nombre de pieces"])307 if not lst.unit_type:308 m = re.search(r"\d\s*(?:½|1/2)|studio|loft",309 payload.get("description") or "", re.I)310 if m:311 lst.unit_type = normalize_unit_type(m.group(0))312313 amenities = list(payload.get("amenities") or [])314 # superficie : texte source (« 902 pi2 ») ajouté aux commodités pour315 # affichage + parsing par finalize(). Quirk du site : le champ316 # contient parfois un type d'unité (« Superficie : 4 ½ »).317 surf = specs.get("superficie") or ""318 if re.search(r"\d\s*(?:pi|m)\b|pi[²2]|m[²2]", surf):319 amenities.append(f"Superficie : {surf}")320 elif surf and not lst.unit_type:321 lst.unit_type = normalize_unit_type(surf)322 if amenities:323 lst.amenities = amenities324325 if payload.get("contact"):326 lst.details = merge_details(lst.details,327 {"contact": payload["contact"]})328329 if payload.get("description"):330 lst.description = payload["description"]331 if payload.get("images"):332 lst.images = payload["images"]333