Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/duquette.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2514#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/duquette.py : connecteur Entreprises Duquette Immobilier91# (duquette.ca). Constructeur-gestionnaire de la Rive-Nord (base à Laval) :92# condos locatifs neufs à Saint-Eustache (320 et 405 chemin de la93# Grande-Côte) et logements à Deux-Montagnes. WordPress + thème WPEstate :94# API REST publique wp-json/wp/v2/estate_property (une fiche par UNITÉ,95# adresse civique en titre), taxonomies property_status (« À louer » /96# « Déjà loué ») et property_city. Le prix ($/mois), la superficie (ft²),97# les sdb et les chambres (libellé property_category « … 2 chambres »,98# dont l'endpoint REST renvoie 500) viennent de la page détail rendue99# serveur (div.price_area, aperçu), via cache detail.100# Granularité UNITÉ, external_id = slug WordPress.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing109from .base import BaseConnector110111BASE = "https://www.duquette.ca"112API = f"{BASE}/wp-json/wp/v2"113114PRICE_RE = re.compile(r"([\d\s ,]{3,9})\$\s*/?\s*mois|"115 r"([\d\s ,]{3,9})\s*\$\s*/mois")116SQFT_RE = re.compile(r"([\d,\s]{2,7})\s*ft\s*2?\b", re.I)117BATH_RE = re.compile(r"(\d+(?:[.,]\d)?)\s*Salles? de bain", re.I)118BED_CAT_RE = re.compile(r"(\d+)\s*chambres?", re.I)119IMG_RE = re.compile(120 r"https://www\.duquette\.ca/wp-content/uploads/[^\"'\s\\)]+?"121 r"\.(?:jpg|jpeg|png|webp)", re.I)122123124def _num(txt: str) -> float | None:125 digits = re.sub(r"[^\d]", "", txt or "")126 return float(digits) if digits else None127128129class DuquetteConnector(BaseConnector):130 source_id = "duquette"131 request_delay = 0.7132133 def _terms(self, taxonomy: str) -> dict[int, str]:134 try:135 data = self.get(f"{API}/{taxonomy}?per_page=100").json()136 except Exception:137 return {}138 return {t["id"]: t["name"] for t in data if isinstance(t, dict)}139140 def _detail_payload(self, url: str) -> dict:141 """Prix, superficie, sdb et photos de la fiche WPEstate."""142 try:143 html = self.get(url).text144 except Exception:145 return {}146 soup = BeautifulSoup(html, "html.parser")147 payload: dict = {}148 area = soup.select_one("div.price_area")149 if area is not None:150 txt = area.get_text(" ", strip=True)151 m = PRICE_RE.search(txt)152 if m:153 price = _num(m.group(1) or m.group(2))154 if price and 300 <= price <= 20000:155 payload["price"] = price156 payload["price_label"] = f"{price:.0f} $ /mois"157 body = soup.get_text(" ", strip=True)158 m = SQFT_RE.search(body)159 if m:160 sqft = _num(m.group(1))161 if sqft and 150 <= sqft <= 5000:162 payload["area_sqft"] = sqft163 m = BATH_RE.search(body)164 if m:165 payload["bathrooms"] = float(m.group(1).replace(",", "."))166 images = [u for u in dict.fromkeys(IMG_RE.findall(html))167 if not re.search(r"logo|favicon|icon|-\d+x\d+\.", u, re.I)]168 if images:169 payload["images"] = images[:20]170 # chambres via le libellé de catégorie (« 320 Grand-Côte 2 chambres »)171 # — l'endpoint REST property_category renvoie 500 chez cet hôte172 for a in soup.select("a[href*='/property_category/']"):173 m = BED_CAT_RE.search(a.get_text(" ", strip=True))174 if m:175 payload["bedrooms"] = float(m.group(1))176 break177 return payload178179 def fetch(self) -> list[Listing]:180 listings: list[Listing] = []181 try:182 props = self.get(f"{API}/estate_property?per_page=100").json()183 except Exception:184 return listings185 if not isinstance(props, list):186 return listings187 status = self._terms("property_status")188 cities = self._terms("property_city")189190 for p in props:191 if not isinstance(p, dict) or p.get("status") != "publish":192 continue193 st = [status.get(i, "") for i in p.get("property_status") or []]194 if not any(s.lower().startswith("à louer") for s in st):195 continue # « Déjà loué »196 slug = p.get("slug") or ""197 url = p.get("link") or ""198 if not slug or not url:199 continue200 title = BeautifulSoup(p.get("title", {}).get("rendered", ""),201 "html.parser").get_text(" ", strip=True)202 address, city = title, ""203 if "," in title:204 address, city = [x.strip() for x in title.rsplit(",", 1)]205 for i in p.get("property_city") or []:206 if cities.get(i):207 city = cities[i]208 break209210 content = BeautifulSoup(p.get("content", {}).get("rendered", ""),211 "html.parser").get_text(" ", strip=True)212213 payload = self.detail(slug, str(p.get("modified", "")),214 lambda u=url: self._detail_payload(u))215216 # chambres via catégorie (page détail) ; studio via le contenu217 bedrooms = payload.get("bedrooms")218 unit_type = ""219 if bedrooms is None and re.match(r"(?i)\W*\w*\s*studio",220 content[:80]):221 unit_type = "Studio"222223 listings.append(Listing(224 source=self.source_id,225 external_id=slug,226 url=url,227 title=title,228 address=address,229 city=city,230 unit_type=unit_type,231 bedrooms=bedrooms,232 bathrooms=payload.get("bathrooms"),233 price=payload.get("price"),234 price_label=payload.get("price_label", ""),235 availability="À louer",236 area_sqft=payload.get("area_sqft"),237 description=content[:2000],238 images=payload.get("images", []),239 ))240 return listings241