SPB Git

Repository Public

le_baronet.py 12.1 KB 285 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/le_baronet.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/le_baronet.py : connecteur Le Baronet (lebaronet.com)91#   Angle rue Notre-Dame Sud / rue Baronet, Sainte-Marie (Beauce,92#   Chaudière-Appalaches) — 87 condos locatifs en 2 phases (phase 1 : 6493#   unités sur 4 étages, 2021 ; phase 2 : 23 unités sur 4 étages, 2023).94#   Site WordPress (Yoast) « one-pager » + pages d'étage rendues CÔTÉ SERVEUR :95#     - phase 1 : /etage-1 … /etage-4 ; phase 2 : /phase2-etages/niveau-1 … 4 ;96#     - chaque page contient un plan SVG dont les ancres `a.c-app` portent97#       data-app-no (n° d'unité), data-app-disponible (« dispo » / « louee »)98#       et un <foreignobject> avec « Grandeur : 4 1/2 » et « Tarif : 1300 $99#       /mois » ; seules les unités « dispo » sont retenues (légende du site :100#       Disponible / Réservé / Loué) ;101#     - ⚠ un popup (`div.c-popUp`) répète en fin de page une copie PÉRIMÉE du102#       plan de l'étage 1 : on ne parse que le SVG de `main.l-etages` ;103#     - fiche unité (/appartements/<no> ou /phase2/<no>, via cache BD) :104#       plan/photo, « DISPONIBLE 1ER JUILLET 2026 » et description.105#   Les numéros d'unités se répètent d'une phase à l'autre (101…, 201…) →106#   external_id préfixé par le chemin de la fiche (appartements-106,107#   phase2-305), stable car issu des slugs WordPress.108#   Aucune adresse civique n'est publiée (« à l'angle de la rue Notre-Dame Sud109#   et de la rue Baronet ») → adresse laissée vide, rien d'inventé.110#   robots.txt : `Disallow:` (vide) → tout est permis ; sitemap Yoast public.111# -----------------------------------------------------------------------------112from __future__ import annotations113114import hashlib115import re116117from bs4 import BeautifulSoup118119from ..schema import Listing, parse_price120from .base import BaseConnector121122BASE = "https://lebaronet.com"123CITY = "Sainte-Marie"124125# pages d'étage : phase 1 puis phase 2 (libellés pour la description)126FLOOR_PAGES: list[tuple[str, str]] = (127    [(f"{BASE}/etage-{i}/", f"Phase 1 — Étage {i}") for i in range(1, 5)]128    + [(f"{BASE}/phase2-etages/niveau-{i}/", f"Phase 2 — Niveau {i}")129       for i in range(1, 5)]130)131132_TYPE_RE = re.compile(r"Grandeur\s*:\s*(\d)\s*1/2\s*(\+?)", re.I)133_PRICE_RE = re.compile(r"Tarif\s*:\s*([\d\s]{2,9})\$", re.I)134_AVAIL_RE = re.compile(r"(?i)^disponible\b")135_IMG_RE = re.compile(136    r'https?://[^"\'\s\)]+/wp-content/uploads/[^"\'\s\)]+'137    r'\.(?:jpg|jpeg|png|webp)', re.I)138_SKIP_IMG = re.compile(r"logo|icon|favicon|hero|-\d{2,4}x\d{2,4}\.", re.I)139140141class LeBaronetConnector(BaseConnector):142    source_id = "le_baronet"143    request_delay = 0.6144    max_details = 30     # plafond de fiches unité (vraies requêtes par sync)145    max_images = 10146147    # -- pages du projet ---------------------------------------------------------148    def _project_info(self) -> tuple[list[str], list[str]]:149        """Commodités (liste « Des services et commodités » de l'accueil,150        `div.o-whiteCol ul li`) et photos du projet (uploads de l'accueil)."""151        amenities: list[str] = []152        images: list[str] = []153        try:154            html = self.get(f"{BASE}/").text155        except Exception:156            return amenities, images157        soup = BeautifulSoup(html, "html.parser")158        for li in soup.select("div.o-whiteCol ul li"):159            t = re.sub(r"\s+", " ", li.get_text(" ", strip=True)).strip()160            if 3 <= len(t) <= 90 and t not in amenities:161                amenities.append(t)162        for u in dict.fromkeys(_IMG_RE.findall(html)):163            if not _SKIP_IMG.search(u) and u not in images:164                images.append(u)165        return amenities[:30], images[: self.max_images]166167    # -- fiche unité ---------------------------------------------------------------168    def _fetch_detail(self, url: str) -> dict:169        """Fiche /appartements/<no> ou /phase2/<no> : disponibilité datée170        (« DISPONIBLE 1ER JUILLET 2026 »), description et plan/photo."""171        if self._fetched >= self.max_details:172            raise RuntimeError("budget de fiches unité atteint")173        self._fetched += 1174        soup = BeautifulSoup(self.get(url).text, "html.parser")175        main = soup.select_one("main.l-app") or soup.select_one("main")176        out: dict = {}177        if main is None:178            return out179180        paras: list[str] = []181        for p in main.select("p"):182            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True)).strip()183            if not t:184                continue185            # 1er paragraphe en gras « DISPONIBLE … » = disponibilité affichée186            if not paras and not out.get("availability") and _AVAIL_RE.match(t):187                out["availability"] = t.capitalize()188                continue189            paras.append(t)190        if paras:191            out["description"] = "\n".join(paras)[:1200]192193        img = main.select_one("img[src]")194        if img and img["src"].startswith("http"):195            out["image"] = img["src"]196        return out197198    # -- fetch -----------------------------------------------------------------199    def fetch(self) -> list[Listing]:200        amenities, project_images = self._project_info()201        self._fetched = 0202203        listings: dict[str, Listing] = {}204        for page_url, floor_label in FLOOR_PAGES:205            try:206                soup = BeautifulSoup(self.get(page_url).text, "html.parser")207            except Exception:208                continue209            # SVG du contenu principal seulement (le popup répète l'étage 1)210            for a in soup.select("main.l-etages a.c-app"):211                try:212                    self._parse_unit(a, page_url, floor_label,213                                     amenities, project_images, listings)214                except Exception:215                    continue216        return list(listings.values())217218    def _parse_unit(self, a, page_url: str, floor_label: str,219                    amenities: list[str], project_images: list[str],220                    listings: dict[str, Listing]) -> None:221        status = (a.get("data-app-disponible") or "").strip().lower()222        num = (a.get("data-app-no") or "").strip()223        href = (a.get("href") or "").strip()224        if not (num and href):225            return226        # seules les unités « dispo » sont des annonces (Réservé/Loué exclus)227        if status != "dispo":228            return229230        # external_id stable : chemin de la fiche (appartements-106, phase2-305)231        ext = href.strip("/").replace("/", "-")232        if ext in listings:233            return234        url = href if href.startswith("http") else f"{BASE}{href}"235236        cell_txt = re.sub(r"\s+", " ", a.get_text(" ", strip=True))237        m = _TYPE_RE.search(cell_txt)238        unit_type = f"{m.group(1)}½" if m else ""239        plus = bool(m and m.group(2))          # « 4½ + » = pièce bureau en sus240        m = _PRICE_RE.search(cell_txt)241        price_label = (re.sub(r"\s+", " ", m.group(0)).strip() + "/mois"242                       if m else "")243244        # fiche unité (cache BD : re-téléchargée seulement si la cellule change)245        cell_key = hashlib.sha1(246            f"{status}|{cell_txt}".encode("utf-8")).hexdigest()247        try:248            detail = self.detail(ext, cell_key,249                                 lambda u=url: self._fetch_detail(u))250        except Exception:251            detail = {}252253        images = list(project_images)254        if detail.get("image") and detail["image"] not in images:255            images.insert(0, detail["image"])256257        desc_bits = [floor_label]258        if plus:259            desc_bits.append("4½ + (pièce pour bureau supplémentaire)")260        if detail.get("description"):261            desc_bits.append(detail["description"])262263        # n° affiché : « 402-2 » est un artefact de slug WordPress, la fiche264        # titre « Appartement no. : 402 » (l'external_id garde le slug complet)265        display_num = re.sub(r"-\d$", "", num)266267        listings[ext] = Listing(268            source=self.source_id,269            external_id=ext,270            url=url,271            title=f"Le Baronet — Appartement {display_num}",272            address="",                     # aucune adresse civique publiée273            sector="",274            city=CITY,275            unit_type=unit_type,276            price=parse_price(price_label),277            price_label=price_label,278            # texte de la fiche (« Disponible 1er juillet 2026 »), sinon le279            # statut de la légende du plan (« Disponible »)280            availability=detail.get("availability", "Disponible"),281            description="\n".join(desc_bits)[:1400],282            amenities=list(amenities),283            images=images[: self.max_images + 1],284        )285
Files main
Menu

Theme