Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/pro_urbain.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-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/pro_urbain.py : connecteur Gestion Pro-Urbain91# (gestionpro-urbain.com). Gestionnaire locatif de Lanaudière / Rive-Nord /92# Grand Montréal (Charlemagne, Repentigny, Berthierville, Saint-Paul,93# Saint-Jacques, Saint-Charles-Borromée…). Site October CMS (plugin maison94# « nerd/realestate ») rendu serveur : /fr/proprietes liste des cartes par95# UNITÉ (adresse, ville, code postal, prix/mois, type n½, sdb, chambres,96# stationnements, disponibilité), page /fr/propriete/<slug> pour la97# description, les inclusions (puces « • ») et les photos (via cache98# detail). Granularité UNITÉ, external_id = slug de la fiche.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type107from .base import BaseConnector108109BASE = "https://gestionpro-urbain.com"110LIST_URL = f"{BASE}/fr/proprietes"111112TYPE_RE = re.compile(r"^\d\s*(?:½|1/2)$")113COUNT_RE = re.compile(r"^\d+(?:[.,]\d)?$")114AVAIL_RE = re.compile(r"Disponibilit[ée]\s*:\s*([^|<]{2,40})", re.I)115IMG_RE = re.compile(116 r"https://gestionpro-urbain\.com/storage/app/uploads/[^\"'\s\\)]+?"117 r"\.(?:jpg|jpeg|png|webp)", re.I)118BULLET_RE = re.compile(r"•\s*([^|<>•]{3,90})")119120121class ProUrbainConnector(BaseConnector):122 source_id = "pro_urbain"123 request_delay = 0.7124125 def _detail_payload(self, url: str) -> dict:126 """Description, inclusions et photos de la fiche /fr/propriete/…"""127 try:128 html = self.get(url).text129 except Exception:130 return {}131 soup = BeautifulSoup(html, "html.parser")132 payload: dict = {}133 images = [u for u in dict.fromkeys(IMG_RE.findall(html))][:20]134 if images:135 payload["images"] = images136 # bloc Description : premier paragraphe substantiel après le titre137 desc = ""138 node = soup.find(string=re.compile(r"^\s*Description\s*$"))139 if node is not None:140 for p in node.find_all_next(["p", "div"]):141 t = p.get_text(" ", strip=True)142 if len(t) > 60:143 desc = t144 break145 if "Caractéristiques" in t:146 break147 if desc:148 payload["description"] = desc[:1500]149 text = soup.get_text("|", strip=True)150 amenities = []151 for b in BULLET_RE.findall(text):152 b = b.strip(" .")153 if b and b not in amenities:154 amenities.append(b)155 if amenities:156 payload["amenities"] = amenities[:25]157 return payload158159 def fetch(self) -> list[Listing]:160 listings: list[Listing] = []161 # Échec du GET de la liste = erreur transitoire à propager (journalisée162 # en échec par ingest), pas un « succès » à 0 annonce.163 html = self.get(LIST_URL).text164 soup = BeautifulSoup(html, "html.parser")165166 seen: set[str] = set()167 for card in soup.select("div.mygrid"):168 link = card.select_one("a[href*='/fr/propriete/']")169 if link is None:170 continue171 url = link["href"]172 slug = url.rstrip("/").rsplit("/", 1)[-1]173 if not slug or slug in seen:174 continue175 seen.add(slug)176177 head = card.select_one(".gsMain h2")178 head_txt = head.get_text(" ", strip=True) if head else ""179 if head_txt and not head_txt.lower().startswith("appartement"):180 continue # commercial/autre : hors sujet181 am = AVAIL_RE.search(head_txt)182 availability = f"Disponibilité : {am.group(1).strip()}" if am else ""183184 addr_p = card.select_one(".gsMain p")185 address = city = postal = ""186 if addr_p is not None:187 parts = [x.strip() for x in188 addr_p.get_text("|", strip=True).split("|") if x.strip()]189 if parts:190 address = parts[0]191 if len(parts) > 1:192 city = parts[1]193 if len(parts) > 2:194 postal = parts[2]195196 price = None197 pr = card.select_one(".currentPrice")198 if pr is not None:199 digits = re.sub(r"[^\d]", "", pr.get_text())200 if digits:201 price = float(digits)202203 # pictogrammes du pied de carte : type n½, sdb, chambres, autos204 unit_type, bathrooms, bedrooms, parking = "", None, None, None205 for ic in card.select(".gsFooter i"):206 img = ic.find("img")207 span = ic.find("span")208 if img is None or span is None:209 continue210 src = img.get("src", "")211 val = span.get_text(" ", strip=True)212 if "room-svgrepo" in src and TYPE_RE.match(val):213 unit_type = normalize_unit_type(val)214 elif "bathtub" in src and COUNT_RE.match(val):215 bathrooms = float(val.replace(",", "."))216 elif "bed-svgrepo" in src and COUNT_RE.match(val):217 bedrooms = float(val)218 elif "car-svgrepo" in src and COUNT_RE.match(val):219 parking = int(val)220221 img = card.select_one(".gsHead img")222 cover = [img["src"]] if img is not None and img.get("src") else []223224 key = f"{price or 0:.0f}-{availability}-{unit_type}"225 payload = self.detail(slug, key,226 lambda u=url: self._detail_payload(u))227228 details: dict = {}229 if parking is not None:230 details["parking"] = parking231 if postal:232 details["postal_code"] = postal233 listings.append(Listing(234 source=self.source_id,235 external_id=slug,236 url=url,237 title=(f"{unit_type} — {address}, {city}"238 if unit_type else f"{address}, {city}"),239 address=address,240 city=city,241 unit_type=unit_type,242 bedrooms=bedrooms,243 bathrooms=bathrooms,244 price=price,245 price_label=f"{price:.0f} $ /mois" if price else "",246 availability=availability,247 description=payload.get("description", ""),248 amenities=payload.get("amenities", []),249 details=details,250 images=payload.get("images") or cover,251 ))252 return listings253