Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/souleymane.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/souleymane.py : connecteur Gestion Souleymane (gestionsouleymane.com)91# Gestionnaire local de Gatineau (secteurs est : Masson-Angers, Buckingham,92# + Hull/Aylmer). WordPress + plugin immobilier ESTATIK : la page /a-louer93# liste toutes les annonces (« 14 results », pas de pagination), chaque94# carte `div.js-es-listing` portant data-post-id (external_id stable),95# l'adresse civique en titre, le prix, chambres/salles de bain et la96# galerie du carrousel (data-lazy). La fiche /property/<slug> (cache BD)97# ajoute la description longue rédigée par l'agence — qui contient98# « 📅 Disponible immédiatement », « secteur Masson-Angers », inclusions —99# exploitée pour availability et le secteur, le reste par textmine.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://gestionsouleymane.com"112LIST_URL = f"{BASE}/a-louer"113114_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)115# secteurs de Gatineau (fusion 2002) repérables dans l'adresse/description116_SECTORS = ["Masson-Angers", "Masson", "Buckingham", "Aylmer", "Hull",117 "Templeton", "Pointe-Gatineau", "Limbour", "Plateau"]118119120class SouleymaneConnector(BaseConnector):121 source_id = "souleymane"122 request_delay = 1.0123 max_details = 25124 max_images = 15125126 # -- helpers ---------------------------------------------------------------127 @staticmethod128 def _sector(*texts: str) -> str:129 for txt in texts:130 for s in _SECTORS:131 if re.search(rf"(?i)\b{re.escape(s)}\b", txt or ""):132 return "Masson-Angers" if s == "Masson" else s133 return ""134135 # -- fiche détail ------------------------------------------------------------136 def _fetch_detail(self, url: str) -> dict:137 self._fetched += 1138 soup = BeautifulSoup(self.get(url).text, "html.parser")139 out: dict = {}140 desc_el = soup.select_one(".es-description, [itemprop='description']")141 # la description complète vit dans la section « Description » ; repli142 # sur le texte principal de la fiche143 block = None144 for h in soup.find_all(["h2", "h3", "h4"]):145 if h.get_text(strip=True).lower().startswith("description"):146 block = h.parent147 break148 el = block or desc_el149 if el:150 txt = el.get_text("\n", strip=True)151 txt = re.sub(r"^(?:Description\s*:?\s*\n?)+", "", txt)152 txt = re.sub(r"\n{2,}", "\n", txt)153 out["description"] = txt.strip()[:2500]154 return out155156 # -- fetch -----------------------------------------------------------------157 def fetch(self) -> list[Listing]:158 soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")159 self._fetched = 0160 listings: dict[str, Listing] = {}161 for card in soup.select("div.js-es-listing"):162 try:163 self._parse_card(card, listings)164 except Exception:165 continue166 return list(listings.values())167168 def _parse_card(self, card, listings: dict[str, Listing]) -> None:169 ext = str(card.get("data-post-id") or "")170 link = card.select_one("h3.es-listing__title a[href]")171 if not link:172 return173 url = link["href"]174 if not ext:175 m = re.search(r"/property/([^/]+)/?", url)176 ext = m.group(1) if m else ""177 if not ext or ext in listings:178 return179180 address = re.sub(r"\s+", " ", link.get_text(" ", strip=True))181 price_el = card.select_one(".es-price")182 price_label = price_el.get_text(" ", strip=True) if price_el else ""183184 excerpt_el = card.select_one("p.es-excerpt")185 excerpt = (re.sub(r"\s+", " ", excerpt_el.get_text(" ", strip=True))186 if excerpt_el else "")187188 beds = ""189 beds_el = card.select_one(".es-listing__meta-bedrooms b")190 if beds_el:191 beds = beds_el.get_text(strip=True)192 baths_el = card.select_one(".es-listing__meta-bathrooms b")193 baths = baths_el.get_text(strip=True) if baths_el else ""194 unit_type = (normalize_unit_type(f"{beds} chambres")195 if beds.isdigit() else "")196 # les maisons restent des maisons, peu importe le compte de pièces197 if re.search(r"(?i)\bmaison\b", excerpt + " " + address):198 unit_type = "Maison"199200 images: list[str] = []201 for img in card.select(".es-listing__image img"):202 u = img.get("data-lazy") or img.get("src") or ""203 if u.startswith("http"):204 u = _SIZE_SUFFIX.sub("", u)205 if u not in images:206 images.append(u)207208 # fiche détail : description complète (cache BD)209 payload: dict = {}210 key = hashlib.sha1(f"{address}|{price_label}|{excerpt}"211 .encode("utf-8")).hexdigest()[:20]212 if self._fetched < self.max_details:213 try:214 payload = self.detail(ext, key,215 lambda u=url: self._fetch_detail(u))216 except Exception:217 payload = {}218 description = payload.get("description") or excerpt219220 # non résidentiel : garages/entreposage/locaux annoncés sur la même page221 head = f"{address} {excerpt} {description[:200]}"222 if re.search(r"(?i)garage à louer|stationnement à louer|entreposage"223 r"|local commercial", head):224 return225226 # « 📅 Disponible immédiatement » / « Disponible le 1er septembre »227 availability = ""228 m = re.search(r"(?i)disponible[^\n.!]{0,50}", description)229 if m:230 availability = m.group(0).strip()231232 details: dict = {}233 if baths.isdigit():234 details["bathrooms"] = int(baths)235236 listings[ext] = Listing(237 source=self.source_id,238 external_id=ext,239 url=url,240 title=address,241 address=address,242 sector=self._sector(address, description),243 city="Gatineau",244 unit_type=unit_type,245 price=parse_price(price_label.replace(",", "")),246 price_label=price_label,247 availability=availability,248 description=description,249 details=details,250 images=images[: self.max_images],251 )252