Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/duproprio.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1713# Last Modified : 2026-08-1814#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/duproprio.py : DuProprio (duproprio.com) — section LOCATION91# ~4 200 annonces de particuliers (sans courtier : zéro chevauchement MLS).92# Découverte par les 21 sitemaps régionaux `sitemaps/fr/<region>-listings.xml.gz`93# filtrés sur `/fr/location/`. Fiches SSR (Laravel/CloudFront, aucun anti-bot) :94# JSON-LD `Apartment` (adresse + code postal + chambres/SDB + amenityFeature)95# et `RealEstateListing` (offers.price + availabilityStarts), lat/lng inline,96# superficie « 970 pi² », galerie dans un JSON échappé ("photos":[…]).97# Fiche retirée -> 302 vers la page parente (détectée par l'URL finale sans98# `/hab-`). Cache détail avec TTL (_detailutil.TtlDetailCache).99# Respect robots.txt : ne jamais toucher /webservice/, /fr-ca/api, /api-proxy.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import gzip104import html as H105import os106import re107108from ..schema import Listing109from .base import BaseConnector110from . import _detailutil as du111112BASE = "https://duproprio.com"113SITEMAP_INDEX = f"{BASE}/sitemaps/fr/index.xml.gz"114115_LOC_RE = re.compile(r"<loc>(.*?)</loc>")116# .../fr/location/<region>/<ville>/<type>-a-louer/hab-<slug>-<ID>117_FICHE_RE = re.compile(118 r"^https://duproprio\.com/fr/location/([a-z0-9-]+)/([a-z0-9-]+)/"119 r"([a-z0-9-]+)-a-louer/hab-[a-z0-9-]+-(\d+)$")120_GEO_RE = re.compile(r'"latitude":([\d.-]+),"longitude":([\d.-]+)')121_AREA_RE = re.compile(r"([\d\s,.]{1,10})\s*pi²")122_PHOTO_RE = re.compile(123 r"photos\\?/public\\?/for_rent\\?/[0-9]+\\?/[0-9]+\\?/[a-z0-9-]+-(\d+)\.jpg")124_PHOTO_FULL_RE = re.compile(125 r"photos[\\/]+public[\\/]+for_rent[\\/]+(\d+)[\\/]+(\d+)[\\/]+([a-z0-9-]+)-(\d+)\.jpg")126_TYPE_HALF_RE = re.compile(r"^(\d+)-1-2$")127128# types non résidentiels (premier mot du slug type) exclus du parc129_EXCLUDED_TYPES = {"commerce", "bureau", "local", "entrepot", "espace",130 "terrain", "garage", "stationnement", "industriel"}131132DETAIL_LIMIT = int(os.environ.get("LOUKA_DUPROPRIO_DETAIL_LIMIT", "800"))133TTL_DAYS = float(os.environ.get("LOUKA_DUPROPRIO_TTL_DAYS", "7"))134MAX_FICHES = int(os.environ.get("LOUKA_DUPROPRIO_MAX", "0")) # 0 = tout135136137def _parse_fiche(html: str) -> dict:138 out: dict = {}139 for node in du.ld_nodes(html):140 t = node.get("@type") or ""141 if t in ("Apartment", "House", "SingleFamilyResidence", "Accommodation"):142 out["title"] = (node.get("name") or "").strip()143 addr = node.get("address") or {}144 out["address"] = (addr.get("streetAddress") or "").strip()145 out["city"] = (addr.get("addressLocality") or "").strip()146 out["postal_code"] = (addr.get("postalCode") or "").strip()147 for src, lab in (("numberOfBedrooms", "Chambres"),148 ("numberOfFullBathrooms", "Salles de bain"),149 ("floorLevel", "Étage")):150 if node.get(src):151 out.setdefault("details", {})[lab] = str(node[src])152 if node.get("numberOfBedrooms"):153 out["bedrooms"] = str(node["numberOfBedrooms"])154 feats = node.get("amenityFeature") or []155 names = [f.get("name", "").strip() for f in feats156 if isinstance(f, dict) and f.get("name")]157 if names:158 out["amenities"] = names159 if node.get("description"):160 out["description"] = H.unescape(str(node["description"])).strip()[:6000]161 elif t == "RealEstateListing":162 offers = node.get("offers") or {}163 try:164 out["price"] = float(str(offers.get("price")).replace(",", "."))165 except (TypeError, ValueError):166 pass167 if offers.get("availabilityStarts"):168 out["availability_date"] = str(offers["availabilityStarts"])[:10]169170 m = _GEO_RE.search(html)171 if m:172 out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))173 m = _AREA_RE.search(html)174 if m:175 try:176 area = float(m.group(1).replace(" ", "").replace(",", ""))177 if 80 <= area <= 20000:178 out["area_sqft"] = area179 except ValueError:180 pass181182 # galerie : URLs (souvent échappées \/) dédupliquées par id photo, en 1600 px183 photos, seen = [], set()184 for m in _PHOTO_FULL_RE.finditer(html):185 ym, lid, slug, pid = m.groups()186 if pid in seen:187 continue188 seen.add(pid)189 # le slug embarque la taille en avant-dernier segment : la re-forcer à 1600190 slug1600 = re.sub(r"-\d+$", "-1600", slug)191 photos.append(f"https://photos.duproprio.com/photos/public/for_rent/"192 f"{ym}/{lid}/{slug1600}-{pid}.jpg")193 if photos:194 out["images"] = photos195196 vt = du.virtual_tour(html) # visite virtuelle (Matterport/iGUIDE…)197 if vt:198 out.setdefault("details", {})["virtual_tour"] = vt199 return out200201202class DuProprioConnector(BaseConnector):203 source_id = "duproprio"204 request_delay = 0.8205206 def _gz(self, url: str) -> str:207 resp = self.get(url)208 try:209 return gzip.decompress(resp.content).decode("utf-8", "replace")210 except (OSError, EOFError):211 return resp.text212213 def _fiche_urls(self) -> list[tuple[str, str, str, str]]:214 """(url, ville, type_slug, id) des fiches location, tous sitemaps."""215 index = self._gz(SITEMAP_INDEX)216 subs = [u for u in _LOC_RE.findall(index) if u.endswith("-listings.xml.gz")]217 out, seen = [], set()218 for sub in subs:219 try:220 xml = self._gz(sub)221 except Exception:222 continue223 for u in _LOC_RE.findall(xml):224 m = _FICHE_RE.match(u)225 if m and m.group(3).split("-")[0] in _EXCLUDED_TYPES:226 continue227 if m and m.group(4) not in seen:228 seen.add(m.group(4))229 out.append((u, m.group(2), m.group(3), m.group(4)))230 return out231232 def _fetch_fiche(self, url: str) -> str:233 """GET d'une fiche ; une redirection vers la page parente = retirée."""234 resp = self.get(url, allow_redirects=True)235 if "/hab-" not in resp.url:236 return "" # 302 « annonce disparue »237 return resp.text238239 @staticmethod240 def _unit_type(type_slug: str, bedrooms: str | None) -> str:241 m = _TYPE_HALF_RE.match(type_slug)242 if m:243 n = int(m.group(1))244 return "6½+" if n >= 6 else f"{n}½"245 base = {"studio": "Studio", "loft": "Loft", "chambre": "Chambre",246 "maison": "Maison", "condo": "", "appartement": ""}247 label = base.get(type_slug.split("-")[0], "")248 if not label and bedrooms and bedrooms.isdigit():249 n = int(bedrooms) + 2250 return "6½+" if n >= 6 else f"{n}½"251 return label or type_slug.replace("-", " ").capitalize()252253 def fetch(self) -> list[Listing]:254 fiches = self._fiche_urls()255 if MAX_FICHES:256 fiches = fiches[:MAX_FICHES]257 cache = du.TtlDetailCache(self, budget=DETAIL_LIMIT, ttl_days=TTL_DAYS,258 fetch_html=self._fetch_fiche)259 out: list[Listing] = []260 try:261 for url, _ville, type_slug, eid in fiches:262 payload = cache.get(eid, url, _parse_fiche)263 if payload is None: # jamais visitée + budget épuisé264 continue265 if not payload or payload.get("gone"):266 continue # fiche retirée (302) ou page vide267 price = payload.get("price")268 # availabilityStarts dans le passé = déjà libre aujourd'hui269 avail = payload.get("availability_date")270 if avail:271 import datetime as _dt272 if avail <= _dt.date.today().isoformat():273 avail = "now"274 # « Ahuntsic (Montréal) » -> secteur + ville ; « X (X) » -> X275 locality = payload.get("city") or ""276 sector = ""277 m = re.match(r"^(.*?)\s*\((.+)\)\s*$", locality)278 if m:279 inner, outer = m.group(1).strip(), m.group(2).strip()280 if inner.lower() == outer.lower():281 locality, sector = inner, ""282 else:283 locality, sector = outer, inner284 lst = Listing(285 source=self.source_id,286 external_id=str(eid),287 url=url,288 title=payload.get("title") or "",289 address=payload.get("address") or "",290 sector=sector,291 city=locality,292 unit_type=self._unit_type(type_slug, payload.get("bedrooms")),293 price=price,294 price_label=(f"{price:,.0f} $/mois".replace(",", " ")295 if price else ""),296 availability_date=avail,297 availability=("Libre immédiatement" if avail == "now"298 else f"Libre le {avail}" if avail else ""),299 area_sqft=payload.get("area_sqft"),300 description=payload.get("description") or "",301 amenities=payload.get("amenities") or [],302 details=payload.get("details") or {},303 images=payload.get("images") or [],304 lat=payload.get("lat"),305 lng=payload.get("lng"),306 )307 low = [a.lower() for a in lst.amenities]308 if any("animaux" in a and "permis" in a for a in low):309 lst.pets = "oui"310 if any(a.startswith("meublé") for a in low):311 lst.furnished = True312 out.append(lst)313 finally:314 cache.close()315 return out316