SPB Git

Repository Public

horizon_terrebonne.py 10.3 KB 261 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/horizon_terrebonne.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/horizon_terrebonne.py : connecteur Horizon Terrebonne91#   (horizonterrebonne.com — Groupe Socam, condos locatifs neufs en 2 tours92#   au 1441 chemin Gascon à Terrebonne). WordPress rendu SERVEUR : la page93#   /condos/ liste des cartes <article class="apartment"> (statut, tour,94#   chambres, prix mensuel, photo, lien) ; chaque fiche « Phase n - x.5 à95#   partir de » ajoute salle(s) de bain, étage, superficie et galerie.96#   Granularité MODÈLE « à partir de » par phase/typologie (pas d'unités97#   individuelles publiées) ; external_id = id du post WordPress (stable,98#   classe post-NNNN). Seules les cartes « Disponible » sont retenues.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type107from .base import BaseConnector108109BASE = "https://horizonterrebonne.com"110LIST_URL = f"{BASE}/condos/"111ADDRESS = "1441, chemin Gascon, Terrebonne"112LAT, LNG = 45.712055, -73.65237113114POST_ID_RE = re.compile(r"\bpost-(\d+)\b")115PRICE_RE = re.compile(r"([\d\s  ]+)\s*\$")116IMG_SIZE_RE = re.compile(r"-\d+x\d+(?=\.(?:jpe?g|png|webp))", re.I)117# « Phase 2 – 4.5 à partir de » -> typologie 4½118TYPE_RE = re.compile(r"(\d)[.,]5")119120121def _price(text: str) -> float | None:122    m = PRICE_RE.search(text or "")123    if not m:124        return None125    try:126        val = float(re.sub(r"[\s  ]", "", m.group(1)))127    except ValueError:128        return None129    return val if 300 <= val <= 20000 else None130131132class HorizonTerrebonneConnector(BaseConnector):133    source_id = "horizon_terrebonne"134    request_delay = 0.8135136    def fetch(self) -> list[Listing]:137        try:138            soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")139        except Exception:140            return []141        listings: list[Listing] = []142        for card in soup.select("article.apartment"):143            status = card.select_one(".apartment__status-value")144            status = status.get_text(strip=True) if status else ""145            if "disponible" not in status.lower() or "non" in status.lower():146                continue147            link = card.select_one("a[href]")148            if not link:149                continue150            url = link["href"]151            m = POST_ID_RE.search(" ".join(card.get("class") or []))152            ext_id = m.group(1) if m else url.rstrip("/").rsplit("/", 1)[-1]153154            tour = card.select_one(".apartment__location-tour")155            tour = tour.get_text(strip=True) if tour else ""156            rooms = card.select_one(".apartment__room-value")157            bedrooms = None158            if rooms:159                try:160                    bedrooms = float(rooms.get_text(strip=True))161                except ValueError:162                    pass163            price_el = card.select_one(".apartment__monthly-price")164            price = _price(price_el.get_text(" ", strip=True)) if price_el else None165166            # fiche détail (cache BD) : titre, sdb, étage, superficie, galerie167            detail = self.detail(ext_id, f"{status}|{price}|{tour}",168                                 lambda u=url: self._detail(u))169            title = detail.get("title") or ""170            unit_type = ""171            m = TYPE_RE.search(title)172            if m:173                unit_type = normalize_unit_type(f"{m.group(1)} 1/2")174            images = detail.get("images") or []175            img = card.select_one(".apartment__image img[src]")176            if img:177                src = IMG_SIZE_RE.sub("", img["src"])178                if src not in images:179                    images = [src] + images180181            details: dict = {}182            if tour:183                details["tour"] = tour184            for k in ("bathrooms", "floor", "orientation"):185                if detail.get(k):186                    details[k] = detail[k]187188            desc_bits = [b for b in (189                f"{title} — {tour}" if tour else title,190                f"Superficie : {detail['area']} pi²" if detail.get("area") else "",191            ) if b]192            listings.append(Listing(193                source=self.source_id,194                external_id=ext_id,195                url=url,196                title=title or f"Condo {unit_type} — Horizon Terrebonne",197                address=ADDRESS,198                city="Terrebonne",199                unit_type=unit_type,200                bedrooms=bedrooms,201                price=price,202                price_label=f"à partir de {price:.0f} $ /mois" if price else "",203                availability=status,204                area_sqft=detail.get("area"),205                description=" | ".join(desc_bits)[:600],206                amenities=detail.get("amenities") or [],207                details=details,208                images=images[:25],209                lat=LAT,210                lng=LNG,211            ))212        return listings213214    # -- page détail « Phase n - x.5 à partir de » ------------------------------215    def _detail(self, url: str) -> dict:216        try:217            soup = BeautifulSoup(self.get(url).text, "html.parser")218        except Exception:219            return {}220        out: dict = {}221        h1 = soup.select_one("h1") or soup.select_one("title")222        if h1:223            out["title"] = re.sub(r"\s*\|.*$", "",224                                  h1.get_text(" ", strip=True)).strip()225        text = soup.get_text(" ", strip=True)226        m = re.search(r"Salle\(s\) de bain\s*(\d+(?:[.,]\d)?)", text)227        if m:228            out["bathrooms"] = float(m.group(1).replace(",", "."))229        m = re.search(r"Étage\(s\)\s*([\w\d]+)", text)230        if m and m.group(1) != "—":231            out["floor"] = m.group(1)232        m = re.search(r"Superficie\s*([\d\s  ]+)\s*pi", text)233        if m:234            try:235                out["area"] = float(re.sub(r"[\s  ]", "",236                                           m.group(1)))237            except ValueError:238                pass239        # avantages de l'immeuble (liste courte avant « Détails du projet »)240        amen: list[str] = []241        for li in soup.select("li"):242            t = li.get_text(" ", strip=True)243            if 3 < len(t) < 60 and re.search(244                    r"piscine|potager|lavage|parc|ascenseur|lounge|"245                    r"entra[iî]nement|terrasse", t, re.I) and t not in amen:246                amen.append(t)247        if amen:248            out["amenities"] = amen[:12]249        imgs: list[str] = []250        for img in soup.select("img[src]"):251            src = img["src"]252            if "/app/uploads/" not in src or re.search(r"logo|icon", src, re.I):253                continue254            src = IMG_SIZE_RE.sub("", src)255            if src.endswith("-scaled.jpg"):256                pass257            if src not in imgs:258                imgs.append(src)259        out["images"] = imgs[:25]260        return out261
Files main
Menu

Theme