Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/place_florimay.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/place_florimay.py : connecteur Place Florimay (placeflorimay.ca)91# Boulevard Taché Ouest, Montmagny (Chaudière-Appalaches) — 170 condos92# locatifs en 3 phases ; seule la phase 2 (60 unités, 5 étages) est exposée93# dans le sélecteur du site.94# Site WordPress (Elementor/Qode) avec le sélecteur d'unités « do1011 »95# (variante du plugin do-selecteur-plans utilisé par La Cour / AULA /96# Le St-Georges), rendu côté serveur :97# - polygones SVG par unité : class disponible / indisponible,98# data-numero (id du contenu WP), data-etage, data-type (« 4½ coin »),99# data-prix, data-promotion ;100# - REST /wp-json/do-selecteur-plans/v1/unite?id=<data-numero> :101# n° d'unité, état (« disponible » / « indisponible » + libellé102# « Louée »), type, superficie habitable et de balcon, plan PDF, galerie.103# Cette variante du plugin ne renvoie PAS de champ `montant` : le loyer104# publié est celui du polygone (data-prix) — aucune autre valeur n'est105# supposée. La carte SVG sert de clé de cache BD (self.detail) : le REST106# n'est rappelé que si l'unité a changé.107# ⚠ Cloudflare renvoie 403 aux robots sans en-tête de navigateur : le108# User-Agent de base.py (Chrome + LouKaBot) passe. robots.txt : Allow: /109# pour les agents génériques (blocage ciblé des robots d'entraînement IA) ;110# signal de contenu « use=reference », compatible avec un agrégateur qui111# renvoie vers la source.112# ⚠ État du marché au 2026-08-09 : les phases 1 et 3 sont complètes et les113# 60 unités de la phase 2 sont toutes « Louée » -> le connecteur retourne114# 0 annonce tant qu'aucune unité n'est remise en location (vérifié aussi115# unité par unité via le REST).116# -----------------------------------------------------------------------------117from __future__ import annotations118119import hashlib120import json121import re122123from bs4 import BeautifulSoup124125from ..schema import Listing, normalize_unit_type, parse_price126from .base import BaseConnector127128BASE = "https://placeflorimay.ca"129SELECTOR_PATH = "/" # le sélecteur d'unités est sur l'accueil130REST_UNIT = f"{BASE}/wp-json/do-selecteur-plans/v1/unite"131NAME = "Place Florimay"132# seule adresse publiée par la source (bureau de location du projet) :133# les adresses civiques par phase ne sont pas affichées sur le site.134ADDRESS = "136, boulevard Taché Ouest, Montmagny, QC G5V 3A5"135CITY = "Montmagny"136137_IMG_RE = re.compile(138 r'https?://[^"\'\s\)]+/wp-content/uploads/[^"\'\s\)]+'139 r'\.(?:jpg|jpeg|png|webp)', re.I)140_SKIP_IMG = re.compile(141 r"logo|icon|favicon|flavicon|cropped-|plan|selecteur"142 r"|-\d{2,4}x\d{2,4}\.", re.I)143144145class PlaceFlorimayConnector(BaseConnector):146 source_id = "place_florimay"147 request_delay = 0.7148 max_rest_units = 70 # garde-fou : appels REST max par sync149 max_images = 10150151 # -- helpers ---------------------------------------------------------------152 @staticmethod153 def _svg_cards(html: str) -> list[tuple[str, dict]]:154 """Unités DISPONIBLES du sélecteur : (data-numero, attributs data-*).155156 Chaque unité apparaît deux fois (polygone + bouton mobile) : dédup par157 data-numero. Les classes « indisponible » (unité louée) sont exclues.158 """159 soup = BeautifulSoup(html, "html.parser")160 cards: list[tuple[str, dict]] = []161 seen: set[str] = set()162 for el in soup.select("[data-numero]"):163 cls = " ".join(el.get("class") or [])164 if not re.search(r"\bdisponible\b", cls) \165 or re.search(r"indisponible|attente", cls):166 continue167 pid = (el.get("data-numero") or "").strip()168 if not pid or pid in seen:169 continue170 seen.add(pid)171 attrs = {k: str(v) for k, v in el.attrs.items()172 if k.startswith("data-")}173 attrs["class"] = cls174 cards.append((pid, attrs))175 return cards176177 @staticmethod178 def _amenities(soup) -> list[str]:179 """Commodités de l'immeuble : items d'icônes du site (structure béton,180 ascenseur, lockers…)."""181 items: list[str] = []182 for el in soup.select(".qodef-icon-list-item .qodef-e-title-text"):183 t = re.sub(r"\s+", " ", el.get_text(" ", strip=True)).strip()184 if 3 <= len(t) <= 90 and t not in items:185 items.append(t)186 return items[:30]187188 def _images(self, html: str) -> list[str]:189 imgs: list[str] = []190 for u in dict.fromkeys(_IMG_RE.findall(html)):191 if not _SKIP_IMG.search(u) and u not in imgs:192 imgs.append(u)193 return imgs[: self.max_images]194195 @staticmethod196 def _sqft(raw) -> float | None:197 s = str(raw or "").strip().replace(" ", "").replace(",", ".")198 try:199 v = float(s)200 except ValueError:201 return None202 return v if 80 <= v <= 20000 else None203204 # -- fetch -----------------------------------------------------------------205 def fetch(self) -> list[Listing]:206 html = self.get(f"{BASE}{SELECTOR_PATH}").text207 soup = BeautifulSoup(html, "html.parser")208 cards = self._svg_cards(html)209 amenities = self._amenities(soup)210 images = self._images(html)211 rest_calls = 0212213 out: list[Listing] = []214 for pid, attrs in cards[: self.max_rest_units]:215 def _fetch(p=pid):216 nonlocal rest_calls217 if rest_calls >= self.max_rest_units:218 raise RuntimeError("budget de requêtes REST atteint")219 rest_calls += 1220 return self.get(REST_UNIT, params={"id": p}).json()221 try:222 # clé de cache BD = attributs du polygone (état, prix, type) :223 # le REST n'est appelé que si l'unité a changé224 key = hashlib.sha1(json.dumps(225 attrs, sort_keys=True).encode()).hexdigest()[:20]226 data = self.detail(pid, key, _fetch)227 except Exception:228 continue229 if not data or data.get("etat") != "disponible":230 continue231232 num = str(data.get("unite") or "").strip() or pid233 t = str(data.get("type") or attrs.get("data-type") or "")234 sup = str(data.get("superficie_habitable") or "").strip()235 terrasse = str(data.get("superficie_terrasse") or "").strip()236 etage = (attrs.get("data-etage") or "").strip()237 style = str(data.get("style") or "").strip()238 chambres = str(data.get("nb_chambres") or "").strip()239240 # prix : cette variante du plugin n'expose pas `montant` -> le241 # loyer publié est celui du polygone du sélecteur242 prix = (attrs.get("data-prix") or "").strip()243 price_label = f"{prix} $ par mois" if prix else ""244245 date_libre = str(data.get("date_libre") or "").strip(" |")246 availability = (f"Libre {date_libre}" if date_libre247 else str(data.get("etat_titre") or "Disponible"))248249 desc = " — ".join(x for x in [250 t, f"{sup} pi²" if sup else "",251 f"balcon {terrasse} pi²" if terrasse else "",252 f"{chambres} chambre(s)" if chambres else "",253 style,254 f"étage {etage}" if etage else ""] if x)255256 details: dict = {}257 if etage.isdigit():258 details["floor"] = int(etage)259 pdf = str(data.get("pdf") or "")260 if pdf.startswith("http"):261 details["plan_pdf"] = pdf262263 imgs = list(images)264 for g in reversed(data.get("gallery") or []):265 gu = g.get("url") if isinstance(g, dict) else str(g or "")266 if gu.startswith("http") and gu not in imgs:267 imgs.insert(0, gu)268269 out.append(Listing(270 source=self.source_id,271 external_id=num,272 url=f"{BASE}{SELECTOR_PATH}#unite-{num}",273 title=f"{NAME} — Unité {num}",274 address=ADDRESS,275 sector="",276 city=CITY,277 unit_type=normalize_unit_type(t),278 price=parse_price(price_label),279 price_label=price_label,280 availability=availability,281 area_sqft=self._sqft(sup),282 description=desc[:600],283 amenities=list(amenities),284 details=details,285 images=imgs[: self.max_images + 2],286 ))287 return out288