Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/lak_nature.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/lak_nature.py : connecteur LAK Appartements Nature91# (lakappartementsnature.ca — 1004, boul. du Lac, Lac-Beauport, près de la92# station Le Relais ; 62 unités locatives, gestion Acropole). WordPress +93# Elementor avec sélecteur de plans « do-selecteur-plans » : chaque unité94# est un <polygon> SVG rendu serveur avec sa classe d'état95# (disponible/indisponible) et ses data-* (data-numero=id interne,96# data-etage, data-type, data-prix, data-promotion). On n'ingère que les97# unités DISPONIBLES ; la fiche JSON /wp-json/do-selecteur-plans/v1/unite98# ?id=<numero> (via cache détail) confirme l'état et fournit le vrai99# numéro d'unité, superficies, plan PDF et galerie.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://lakappartementsnature.ca"112JSON_URL = f"{BASE}/wp-json/do-selecteur-plans/v1/unite"113114ADDRESS = "1004, boulevard du Lac, Lac-Beauport, G3B 2T4"115CITY = "Lac-Beauport"116117# photos de l'immeuble dans la page (hors logos/icônes/plans)118IMG_RE = re.compile(r'(?:src|href)="(https://lakappartementsnature\.ca/'119 r'wp-content/uploads/[^"]+\.(?:jpe?g|png|webp))"', re.I)120121122class LakNatureConnector(BaseConnector):123 source_id = "lak_nature"124 request_delay = 0.6125 max_details = 40 # garde-fou fiches JSON (vraies requêtes par sync)126127 def fetch(self) -> list[Listing]:128 listings: list[Listing] = []129 html = self.get(f"{BASE}/").text130 soup = BeautifulSoup(html, "html.parser")131 self._fetched = 0132133 building_images = [u for u in dict.fromkeys(IMG_RE.findall(html))134 if not re.search(r"logo|icon|favicon|plan|Lak_plan",135 u, re.I)][:12]136137 details_common: dict = {}138 phones = dict.fromkeys(re.findall(r'href="tel:\+?1?(\d{10})"', html))139 if phones:140 d10 = next(iter(phones))141 details_common["contact"] = {142 "phone": f"{d10[:3]}-{d10[3:6]}-{d10[6:]}"}143144 # polygones SVG du sélecteur : un par unité (dupliqués desktop/mobile)145 seen: set[str] = set()146 for poly in soup.find_all("polygon"):147 try:148 classes = " ".join(poly.get("class") or [])149 numero = (poly.get("data-numero") or "").strip()150 if not numero or numero in seen:151 continue152 seen.add(numero)153 # on n'ingère que les unités encore offertes154 if "indisponible" in classes or "disponible" not in classes:155 continue156157 unit_type = normalize_unit_type(158 poly.get("data-type") or "")159 price = parse_price(poly.get("data-prix") or "")160 floor = (poly.get("data-etage") or "").strip()161 promo = (poly.get("data-promotion") or "").strip()162163 # fiche JSON de l'unité : vrai numéro, état confirmé,164 # superficies, plan PDF, galerie165 ext_id = numero166 availability = "Disponible"167 area = None168 images = list(building_images)169 details = dict(details_common)170 amenities: list[str] = []171 key = hashlib.sha1(172 f"{numero}|{classes}|{price}".encode()).hexdigest()173 try:174 d = self.detail(numero, key,175 lambda n=numero: self._unite_json(n))176 except Exception:177 d = {}178 if d:179 if d.get("etat") and d["etat"] != "disponible":180 continue # l'API fait foi sur l'état181 if d.get("unite"):182 ext_id = str(d["unite"])183 if d.get("date_libre"):184 availability = str(d["date_libre"])185 try:186 v = float(str(d.get("superficie_habitable") or "")187 .replace(" ", "").replace(",", "."))188 if 200 <= v <= 3000:189 area = v190 except ValueError:191 pass192 if d.get("superficie_terrasse"):193 amenities.append(194 f"Terrasse : {d['superficie_terrasse']} pi²")195 if d.get("style"):196 amenities.append(f"Style : {d['style']}")197 if d.get("pdf"):198 details["plan_pdf"] = d["pdf"]199 gal = [u for u in (d.get("gallery") or [])200 if isinstance(u, str)]201 if gal:202 images = gal + building_images203 if promo:204 amenities.append(f"Promotion : {promo}")205 if floor:206 amenities.append(f"Étage : {floor}")207208 listings.append(Listing(209 source=self.source_id,210 external_id=ext_id,211 url=f"{BASE}/",212 title=f"{unit_type} — unité {ext_id}, "213 f"LAK Appartements Nature",214 address=ADDRESS,215 city=CITY,216 unit_type=unit_type,217 price=price,218 availability=availability,219 area_sqft=area,220 amenities=amenities,221 details=details,222 images=images[:20],223 ))224 except Exception:225 continue226 return listings227228 # -- fiche JSON d'une unité (endpoint du plugin do-selecteur-plans) ----------229 def _unite_json(self, numero: str) -> dict:230 if self._fetched >= self.max_details:231 raise RuntimeError("budget de fiches JSON atteint")232 self._fetched += 1233 d = self.get(f"{JSON_URL}?id={numero}").json()234 return d if isinstance(d, dict) else {}235