SPB Git

Repository Public

promenade_des_forts.py 10.7 KB 257 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/promenade_des_forts.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# 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/promenade_des_forts.py : connecteur Promenade des Forts91#   (promenadedesforts.com, Groupe immobilier Brochu) — condos locatifs en92#   2 phases au 6275 et 6375, boulevard Étienne-Dallaire (quartier Umano,93#   Lévis). Site WordPress rendu serveur : chaque page d'étage94#   (/projets/phase-N/etage-M/) contient un plan SVG dont les liens d'unités95#   portent la classe « disponible » ou « loue ». La fiche de chaque unité96#   disponible donne modèle, grandeur (4½…), superficie totale, prix avec date97#   (« disponible 1er septembre 2026 à 1485 $ »), spécifications, plan et PDF.98#   Peu d'unités libres à la fois : les fiches sont visitées directement à99#   chaque sync (pas de cache détail), ~15-20 requêtes au total.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, infer_city, normalize_unit_type, parse_area_sqft108from .base import BaseConnector109110BASE = "https://www.promenadedesforts.com"111PHASES = (1, 2)112SECTOR = "Quartier Umano (Lévis)"113114# lien d'unité disponible sur le plan SVG d'une page d'étage115_UNIT_LINK_RE = re.compile(116    r'<a\s[^>]*href="(https?://[^"]*/projets/phase-\d+/etage-\d+/unite-\d+/?)"'117    r'[^>]*class="disponible"', re.I)118# pages d'étages listées dans la navigation d'une page de phase119_FLOOR_LINK_RE = re.compile(120    r'href="(https?://[^"]*/projets/phase-\d+/etage-\d+/?)"')121# adresse civique du pied de page (« 6275 et 6375, Boulevard Étienne-Dallaire,122# Levis, QC »)123_ADDR_RE = re.compile(r"(\d{4}\s+et\s+\d{4},?\s+[Bb]oulevard[^,<]+,\s*L[eé]vis)")124125126class PromenadeDesFortsConnector(BaseConnector):127    source_id = "promenade_des_forts"128    request_delay = 0.7129    max_floor_pages = 20      # garde-fou (2 phases x 6 étages aujourd'hui)130    max_unit_pages = 40       # garde-fou sur les fiches d'unités131132    # -- fiche d'une unité disponible -------------------------------------------133    def _parse_unit(self, url: str, html: str) -> Listing | None:134        soup = BeautifulSoup(html, "html.parser")135        m = re.search(r"phase-(\d+)/etage-(\d+)/unite-(\d+)", url)136        if not m:137            return None138        phase, floor, num = m.group(1), m.group(2), m.group(3)139140        # champs étiquetés de la fiche : « Modèle : », « Grandeur : »,141        # « Superficie totale : », « Prix : » (p.margin-bottom-0 puis p.h3)142        fields: dict[str, str] = {}143        for p in soup.select(".infosUnite p.margin-bottom-0"):144            label = p.get_text(" ", strip=True).rstrip(" :").lower()145            val = p.find_next_sibling("p")146            if label and val is not None:147                fields[label] = re.sub(r"\s+", " ", val.get_text(" ", strip=True))148149        # spécifications : liste à puces qui suit l'étiquette « Spécifications »150        amenities: list[str] = []151        for p in soup.select(".infosUnite p.margin-bottom-0"):152            if "spécifications" in p.get_text(strip=True).lower():153                ul = p.find_next("ul")154                if ul:155                    amenities = [re.sub(r"\s+", " ", li.get_text(" ", strip=True))156                                 for li in ul.find_all("li")]157                break158159        # statut affiché sur la fiche (« Disponible » avec crochet vert)160        statut = soup.select_one(".infosUnite span.disponible")161        if statut is None:162            return None            # l'étage l'annonçait libre, la fiche non163164        # prix : « disponible 1er septembre 2026 à 1485 $ » ou « 1945 $ » —165        # le libellé complet sert aussi de disponibilité (date incluse)166        price_label = fields.get("prix", "")167        availability = (price_label if "disponible" in price_label.lower()168                        else statut.get_text(" ", strip=True))169170        desc: list[str] = []171        if fields.get("modèle"):172            desc.append(f"Modèle : {fields['modèle']}")173        pdf = soup.select_one('a.button[href$=".pdf"]')174        if pdf:175            desc.append(f"Fiche PDF : {pdf['href']}")176177        # plan de l'unité (image de la colonne de droite)178        images = []179        img = soup.select_one(".col-md-8 img[src]")180        if img and str(img["src"]).startswith("http"):181            images.append(str(img["src"]))182183        # adresse et contact du pied de page (présents sur chaque page)184        addr_m = _ADDR_RE.search(html)185        address = addr_m.group(1) if addr_m else ""186        contact: dict = {}187        tel = re.search(r'href="tel:([\d\s\-.]{10,14})"', html)188        if tel:189            d = re.sub(r"\D", "", tel.group(1))[-10:]190            if len(d) == 10:191                contact["phone"] = f"{d[:3]}-{d[3:6]}-{d[6:]}"192        mail = re.search(r'href="mailto:([^"?]+)"', html)193        if mail:194            contact["email"] = mail.group(1).strip()195196        details: dict = {"floor": int(floor)}197        if contact:198            details["contact"] = contact199200        unit_type = normalize_unit_type(fields.get("grandeur", ""))201        return Listing(202            source=self.source_id,203            external_id=f"phase-{phase}-unite-{num}",204            url=url,205            title=f"Promenade des Forts phase {phase} — unité {num}"206                  f" ({unit_type})" if unit_type else207                  f"Promenade des Forts phase {phase} — unité {num}",208            address=address,209            sector=SECTOR,210            city=infer_city(SECTOR, default="Lévis"),211            unit_type=unit_type,212            price=None,                      # dérivé du libellé par finalize()213            price_label=price_label,214            availability=availability,215            area_sqft=parse_area_sqft(fields.get("superficie totale", "")),216            description=" | ".join(desc),217            amenities=amenities,218            details=details,219            images=images,220        )221222    def fetch(self) -> list[Listing]:223        # 1) Pages d'étages découvertes depuis les pages de phases224        floor_urls: list[str] = []225        for phase in PHASES:226            try:227                html = self.get(f"{BASE}/projets/phase-{phase}/").text228            except Exception:229                continue230            for u in _FLOOR_LINK_RE.findall(html):231                u = u.rstrip("/") + "/"232                if u not in floor_urls:233                    floor_urls.append(u)234235        # 2) Unités marquées « disponible » sur le plan SVG de chaque étage236        unit_urls: list[str] = []237        for floor_url in floor_urls[:self.max_floor_pages]:238            try:239                html = self.get(floor_url).text240            except Exception:241                continue242            for u in _UNIT_LINK_RE.findall(html):243                u = u.rstrip("/") + "/"244                if u not in unit_urls:245                    unit_urls.append(u)246247        # 3) Fiche de chaque unité disponible (prix, date, superficie, specs)248        listings: list[Listing] = []249        for url in unit_urls[:self.max_unit_pages]:250            try:251                lst = self._parse_unit(url, self.get(url).text)252            except Exception:253                continue254            if lst is not None:255                listings.append(lst)256        return listings257
Files main
Menu

Theme