Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/quartier_plus.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# 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/quartier_plus.py : connecteur Le Quartier Plus (lequartierplus.com91# — Thetford Mines, Chaudière-Appalaches). Complexe locatif 55+ autonome92# (aucun service de repas/soins : appartements standards, lofts urbains et93# unités bigénérationnelles) construit en 3 phases ; la page94# /plans-et-visites-virtuelles/ embarque un sélecteur d'étages WordPress95# (thème ubeo-theme-v5-child) dont TOUTES les unités sont rendues serveur :96# blocs `div.unit#unit_<n>` avec numéro, statut (« disponible », « Construction97# 2026 »…), type (3½/4½/4½+/5½), lettre de modèle, superficie du logement et98# du balcon, plan PNG/PDF. Seules les unités dont le statut contient99# « disponible » sont retenues. Aucun prix par unité, MAIS la page publie100# des boîtes « info-box » par type (3½ / 4½ / 4½+ et 5½) avec « À partir de101# X$/mois », plage de superficies et caractéristiques -> price_label par102# type (prix plancher, convention « à partir de » du schéma) + description.103# Adresses (page /contact/) : phases 1-2 = 180, rue Kingsville ; phase 3104# (statut « Construction 2026 ») = 140, rue Kingsville — G6G 0S7.105# Photos : le site n'a pas de galerie par unité (plan PNG seulement) ; on106# ajoute la vue de l'immeuble (plans) et la photo de la bâtisse (/contact/).107# external_id stable : numéro d'unité (unit_501 -> 501).108# robots.txt Yoast ouvert (Disallow vide), sitemap public.109# -----------------------------------------------------------------------------110from __future__ import annotations111112import re113114from bs4 import BeautifulSoup115116from ..schema import Listing, normalize_unit_type117from .base import BaseConnector118119BASE = "https://www.lequartierplus.com"120LIST_URL = f"{BASE}/plans-et-visites-virtuelles/"121CONTACT_URL = f"{BASE}/contact/"122123# adresses publiées sur /contact/ (repli si la page devient inaccessible)124_PHASE12_ADDR = "180, rue Kingsville, Thetford Mines (Québec) G6G 0S7"125_PHASE3_ADDR = "140, rue Kingsville, Thetford Mines (Québec) G6G 0S7"126127_AREA_RE = re.compile(r"([\d\s,]+)\s*p")128# jeton de type dans le titre d'une info-box : « 3 1/2 », « 4 1/2 + », « 5 1/2 »129_BOX_TYPE_RE = re.compile(r"(\d)\s*(?:1/2|½)\s*(\+?)")130131132def _sqft(text: str) -> float | None:133 """« 1 097 p2 » -> 1097.0 (None si illisible)."""134 m = _AREA_RE.search(text)135 if not m:136 return None137 try:138 return float(m.group(1).replace(" ", "").replace(" ", "")139 .replace(",", "."))140 except ValueError:141 return None142143144class QuartierPlusConnector(BaseConnector):145 source_id = "quartier_plus"146 request_delay = 0.6147148 # -- boîtes « info-box » par type : prix plancher + superficies + attraits --149 @staticmethod150 def _type_boxes(soup) -> dict[str, dict]:151 """{"3½": {"price_label": "À partir de 1195$/mois", "text": …}, …}152 (la boîte « 4 1/2 + et 5 1/2 » alimente les clés 4½+ ET 5½)."""153 boxes: dict[str, dict] = {}154 for bloc in soup.select(".kt-infobox-textcontent"):155 title_el = bloc.select_one(".kt-blocks-info-box-title")156 body_el = bloc.select_one(".kt-blocks-info-box-text")157 if not (title_el and body_el):158 continue159 title = title_el.get_text(" ", strip=True)160 body = re.sub(r"\s+", " ", body_el.get_text(" ", strip=True))161 body = body.replace(" pi 2", " pi²").strip()162 m = re.search(r"(À partir de[\d\s]+\$\s*/\s*mois)", body)163 price_label = re.sub(r"\s+", " ", m.group(1)) if m else ""164 for n, plus in _BOX_TYPE_RE.findall(title):165 key = f"{n}½{'+' if plus else ''}"166 boxes.setdefault(key, {"price_label": price_label,167 "text": body})168 return boxes169170 # -- photos du complexe (page contact) + vue de l'immeuble (page plans) ----171 def _complex_photos(self, plans_soup) -> list[str]:172 photos: list[str] = []173 full = plans_soup.select_one('img[src*="full_building"]')174 if full and str(full.get("src", "")).startswith("http"):175 photos.append(full["src"])176 try:177 csoup = BeautifulSoup(self.get(CONTACT_URL).text, "html.parser")178 except Exception:179 return photos180 self._contact_soup = csoup181 for img in csoup.select('img[src*="/wp-content/uploads/"]'):182 u = str(img.get("src") or "")183 if re.search(r"batisse|logement", u, re.I) and u.startswith("http") \184 and u not in photos:185 photos.append(u)186 return photos[:3]187188 def fetch(self) -> list[Listing]:189 html = self.get(LIST_URL).text190 soup = BeautifulSoup(html, "html.parser")191 self._boxes = self._type_boxes(soup)192 self._contact_soup = None193 self._photos = self._complex_photos(soup)194 self._addresses = self._phase_addresses()195196 listings: dict[str, Listing] = {}197 for unit in soup.select("div.unit[id^=unit_]"):198 try:199 self._parse_unit(unit, listings)200 except Exception:201 continue202 return list(listings.values())203204 # -- adresses par phase (page /contact/, avec repli) ------------------------205 def _phase_addresses(self) -> dict[str, str]:206 addrs = {"12": _PHASE12_ADDR, "3": _PHASE3_ADDR}207 if self._contact_soup is None:208 return addrs209 text = self._contact_soup.get_text("\n", strip=True)210 for label, key in ((r"Phase\s*1\s*et\s*2", "12"), (r"Phase\s*3", "3")):211 m = re.search(label + r"\n(\d{2,4}[^\n]+)\n"212 r"Thetford Mines[^\n]*\n?([A-Z]\d[A-Z]\s?\d[A-Z]\d)?",213 text)214 if m:215 cp = f" {m.group(2)}" if m.group(2) else ""216 addrs[key] = f"{m.group(1).strip()}, Thetford Mines (Québec){cp}"217 return addrs218219 # -- bloc unité (div.unit#unit_<n>) ------------------------------------------220 def _parse_unit(self, unit, listings: dict[str, Listing]) -> None:221 ext_id = unit.get("id", "").removeprefix("unit_").strip()222 if not ext_id or ext_id in listings:223 return224225 header = unit.select_one("p.details_header")226 if header is None:227 return228 name_el = header.select_one("span.has-wpdc-x-large-font-size")229 name = name_el.get_text(" ", strip=True) if name_el else f"Unité {ext_id}"230 status_el = header.select_one("span.has-wpdc-medium-font-size")231 availability = re.sub(232 r"\s+", " ",233 status_el.get_text(" ", strip=True)) if status_el else ""234235 # seules les unités affichées « disponible » sont des annonces236 if "disponible" not in availability.lower():237 return238 if "indisponible" in availability.lower() or re.search(239 r"(?i)lou[ée]|réserv", availability):240 return241242 # colonnes du bloc unit_details : type (badge), modèle, superficies243 unit_label, model, area, balcony = "", "", None, None244 for col in unit.select(".unit_details > div"):245 txt = re.sub(r"\s+", " ", col.get_text(" ", strip=True))246 label = ""247 small = col.select_one(".small_text")248 if small:249 label = small.get_text(" ", strip=True).upper()250 if "SUPERFICIE" in label:251 area = _sqft(txt)252 elif "BALCON" in label:253 balcony = _sqft(txt)254 elif "TYPE" in label:255 strong = col.select_one("strong")256 model = strong.get_text(strip=True) if strong else ""257 elif re.match(r"^[1-6]½", txt):258 unit_label = txt259260 amenities: list[str] = []261 if model:262 amenities.append(f"Modèle {model}")263 if balcony:264 amenities.append(f"Balcon {balcony:g} pi²")265266 # plan du logement (PNG du sélecteur) + photos du complexe267 images: list[str] = []268 plan = unit.select_one("p.unit_plan img[src]")269 if plan:270 u = plan["src"]271 if u.startswith("/"):272 u = BASE + u273 if u.startswith("http"):274 images.append(u)275 images.extend(u for u in self._photos if u not in images)276277 # adresse selon la phase : « Construction 2026 » = phase 3 (140,278 # Kingsville), le reste = phases 1-2 (180, Kingsville) — page /contact/279 if "construction 2026" in availability.lower():280 address = self._addresses["3"]281 else:282 address = self._addresses["12"]283284 # prix plancher + description publiés par type (info-box de la page)285 key = unit_label.replace(" ", "")286 box = self._boxes.get(key) or {}287 price_label = box.get("price_label", "")288 desc_bits = []289 if box.get("text"):290 desc_bits.append(f"Type {unit_label} au Quartier Plus : "291 f"{box['text']}")292 desc_bits.append("Le Quartier Plus est un complexe locatif pour "293 "personnes de 55 ans et plus autonomes (sans service "294 "de repas ni de soins), rue Kingsville à Thetford "295 "Mines : appartements neufs et lofts urbains à aires "296 "ouvertes, standards ou bigénérationnels.")297 if model:298 desc_bits.append(f"Modèle {model}"299 + (f", superficie {area:g} pi²" if area else "")300 + (f", balcon {balcony:g} pi²." if balcony else "."))301302 title = f"Le Quartier Plus — {name}"303 if unit_label:304 title += f" ({unit_label})"305306 listings[ext_id] = Listing(307 source=self.source_id,308 external_id=ext_id,309 url=LIST_URL,310 title=title,311 address=address,312 city="Thetford Mines",313 unit_type=normalize_unit_type(unit_label.replace("+", "")),314 price=None, # prix plancher du type via label315 price_label=price_label, # « À partir de X$/mois » (par type)316 availability=availability,317 area_sqft=area,318 description=" ".join(desc_bits),319 amenities=amenities,320 images=images,321 )322