Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/terra.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0814#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/terra.py : connecteur TERRA Condos locatifs (terracondolocatif.ca)91# Projet de 4 phases sur la route Mgr-Bourget (arrondissement Desjardins,92# Lévis). Site Webflow : chaque page de phase liste les unités par immeuble93# avec statut Disponible/Réservée/Louée (classes w-condition-invisible).94# Prix « à partir de » par type affichés en entête (3½+/4½+).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import re99100from bs4 import BeautifulSoup101102from ..schema import Listing, infer_city, normalize_unit_type, parse_price103from .base import BaseConnector104105BASE = "https://www.terracondolocatif.ca"106PHASES = {107 "phase-1-2": "Phases 1-2",108 "phase-3": "Phase 3",109 "phase-4": "Phase 4",110}111SECTOR = "Desjardins (Lévis)"112113# images générales du projet (photo + plan d'ensemble)114_GALLERY_RE = re.compile(115 r'https://cdn\.prod\.website-files\.com/[^"\s,]+\.(?:jpg|jpeg|webp)', re.I)116117118class TerraConnector(BaseConnector):119 source_id = "terra"120 request_delay = 0.6121122 def fetch(self) -> list[Listing]:123 listings: dict[str, Listing] = {}124125 for slug, phase_name in PHASES.items():126 try:127 html = self.get(f"{BASE}/{slug}").text128 except Exception:129 continue130 soup = BeautifulSoup(html, "html.parser")131132 # contact du projet (liens tel:/mailto: de la page)133 contact: dict = {}134 tel = soup.select_one("a[href^='tel:']")135 if tel:136 digits = re.sub(r"\D", "", tel.get("href", ""))[-10:]137 if len(digits) == 10:138 contact["phone"] = f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"139 mail = soup.select_one("a[href^='mailto:']")140 if mail:141 m = re.match(r"mailto:([^?]+)", mail.get("href", ""))142 if m:143 contact["email"] = m.group(1).strip()144145 # Prix « à partir de » par type (ex. "3 1/2 + à partir de 1185 $/mois")146 type_prices: dict[str, tuple[float | None, str]] = {}147 for m in re.finditer(r"(\d)\s*1/2\s*\+?\s*à partir de\s*"148 r"([\d\s ]+)\$\s*/\s*mois",149 soup.get_text(" ", strip=True)):150 label = (f"{m.group(1)}½ à partir de "151 f"{m.group(2).strip()} $/mois")152 type_prices[m.group(1)] = (parse_price(f"{m.group(2)}$"), label)153154 # Galerie générale (photo du projet)155 gallery = [u for u in dict.fromkeys(_GALLERY_RE.findall(html))156 if not re.search(r"logo|favicon|icon", u, re.I)][:3]157158 # Onglets = immeubles ("Le 939", "Le 943", ...)159 for pane in soup.select("div.w-tab-pane"):160 building = (pane.get("data-w-tab") or "").strip()161 for card in pane.select("div.listeunitecms"):162 try:163 lst = self._parse_card(card, building, slug,164 phase_name, type_prices,165 gallery, contact)166 if lst and lst.external_id not in listings:167 listings[lst.external_id] = lst168 except Exception:169 continue170171 return list(listings.values())172173 def _parse_card(self, card, building, slug, phase_name,174 type_prices, gallery, contact) -> Listing | None:175 # Statut : disponible si .tagdispo n'a PAS la classe w-condition-invisible176 tag = card.select_one(".tagdispo")177 if tag is None or "w-condition-invisible" in tag.get("class", []):178 return None179180 text = card.get_text(" ", strip=True)181 num_m = re.search(r"\(\s*(\d+)\s*\)", text)182 if not num_m:183 return None184 unit_no = num_m.group(1)185186 type_m = re.search(r"(\d\s*1/2\s*\+?)", text)187 raw_type = type_m.group(1) if type_m else ""188 unit_type = normalize_unit_type(raw_type)189190 floor_m = re.search(r"(RDC|Étage\s*\d+)", text)191 sqft_m = re.search(r"(\d{3,4})\s*pi", text)192 beds_m = re.search(r"(\d+)\s*chambres?", text)193 expo_m = re.search(r"Exposition\s+([\w.]+)", text)194 model_m = re.search(r"Type\s+([\w.]+)", text)195196 # Fiche PDF de l'unité (le lien visible), ex. .../Fiche_939-101.pdf,197 # .../FIche_943-402.pdf ou .../68f5..._951-106.pdf198 fiche = ""199 for a in card.select("a.buttonplans[href]"):200 href = a.get("href", "")201 if href.startswith("http") and href.lower().endswith(".pdf"):202 fiche = href203 break204 fm = re.search(r"(\d{3})-(\d{3})\.pdf$", fiche, re.I)205 if fm:206 building = fm.group(1)207 unit_no = fm.group(2)208 elif not building.isdigit():209 # sans fiche ni onglet d'immeuble (onglet d'étage) : doublon210 return None211212 digit = re.search(r"(\d)", raw_type)213 price, price_label = (None, "")214 if digit and digit.group(1) in type_prices:215 price, price_label = type_prices[digit.group(1)]216217 desc_parts = []218 if floor_m:219 desc_parts.append(floor_m.group(1))220 if sqft_m:221 desc_parts.append(f"{sqft_m.group(1)} pi²")222 if beds_m:223 desc_parts.append(f"{beds_m.group(1)} chambre(s)")224 if expo_m:225 desc_parts.append(f"Exposition {expo_m.group(1)}")226 if model_m:227 desc_parts.append(f"Modèle {model_m.group(1)}")228 if fiche:229 desc_parts.append(f"Fiche : {fiche}")230231 ext_id = f"{building or slug}-{unit_no}"232 address = (f"{building}, route Mgr-Bourget, Lévis"233 if building.isdigit() else "route Mgr-Bourget, Lévis")234235 return Listing(236 source=self.source_id,237 external_id=ext_id,238 url=f"{BASE}/{slug}",239 title=f"TERRA {phase_name} — Le {building}, unité {unit_no}"240 f" ({unit_type})",241 address=address,242 sector=SECTOR,243 city=infer_city(SECTOR, default="Lévis"),244 unit_type=unit_type,245 price=price,246 price_label=price_label,247 availability="Disponible",248 description=" | ".join(desc_parts),249 # « Formule tout inclus » affichée sur le site (accueil + pages250 # de phase) : chauffé et climatisé, eau chaude, internet,251 # stationnement intérieur, ascenseur ; « plafonds de 9 pieds,252 # balcons de 134 à 254 pi², salle commune » (pied des pages phase).253 amenities=["Chauffé et climatisé", "Eau chaude incluse",254 "Internet inclus", "Stationnement intérieur",255 "Ascenseur", "Balcon", "Salle commune",256 "Plafonds de 9 pieds"],257 details={"contact": contact} if contact else {},258 images=list(gallery),259 )260