SPB Git

Repository Public

complexe_st_charles.py 9.2 KB 229 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/complexe_st_charles.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/complexe_st_charles.py : connecteur Complexe St-Charles91#   (complexestcharles.ca — condos locatifs neufs en 7 phases, 130 à 190 rue92#   de la Pruche à Terrebonne, ~200 unités). Site Wix mais rendu SERVEUR93#   (curl suffit) : l'accueil publie les prix « à partir de » par typologie94#   (3½/4½/5½) et le menu la liste des phases (« 190 - PHASE 2 » -> adresse95#   civique) ; chaque page /phase-N détaille les modèles par typologie96#   (« Unité A-03 · 104, 204, 304 & 404 »). Granularité TYPOLOGIE par phase97#   (aucune unité individuelle ni disponibilité publiée) ; external_id =98#   « phase-N-typologie » (stable). Les phases annoncées « À VENIR » sur99#   l'accueil (7 et 8 en 2026) sont exclues.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type108from .base import BaseConnector109110BASE = "https://www.complexestcharles.ca"111STREET = "rue de la Pruche"112CITY = "Terrebonne"113114# « 190 - PHASE 2 » (menu) -> numéro civique + numéro de phase115MENU_RE = re.compile(r"(\d{2,4})\s*-?\s*PHASE\s*(\d+)", re.I)116# « 3 1/2 ... A partir de 1 500$ / mois » (accueil)117PRICE_RE = re.compile(118    r"([1-6])\s*1/2\s*A partir de\s*([\d\s  ]+)\$\s*/\s*mois", re.I)119# « PHASE 7 ET PHASE 8 À VENIR » (accueil) -> phases exclues120COMING_RE = re.compile(r"PHASE\s*(\d+)(?:\s*ET\s*PHASE\s*(\d+))?\s*"121                       r"[ÀA]\s*VENIR", re.I)122TYPO_RE = re.compile(r"^([1-6])\s*1/2$")123UNIT_RE = re.compile(r"^Unité\s+([\w\-]+)\s*(.*)$", re.I)124WIX_IMG_RE = re.compile(125    r"https://static\.wixstatic\.com/media/([\w~%]+\.(?:jpe?g|png|webp))")126127128class ComplexeStCharlesConnector(BaseConnector):129    source_id = "complexe_st_charles"130    request_delay = 0.8131132    def fetch(self) -> list[Listing]:133        try:134            home = self.get(f"{BASE}/").text135        except Exception:136            return []137        soup = BeautifulSoup(home, "html.parser")138        text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))139140        # prix « à partir de » par typologie (affichés sur l'accueil seulement)141        prices: dict[str, float] = {}142        for m in PRICE_RE.finditer(text):143            try:144                prices[f"{m.group(1)}½"] = float(145                    re.sub(r"[\s  ]", "", m.group(2)))146            except ValueError:147                pass148149        # phases « à venir » (pas encore louables) -> exclues150        coming: set[str] = set()151        m = COMING_RE.search(text)152        if m:153            coming = {g for g in m.groups() if g}154155        # menu : « 190 - PHASE 2 » -> {phase: numéro civique}156        phases: dict[str, str] = {}157        for m in MENU_RE.finditer(text):158            phases.setdefault(m.group(2), m.group(1))159160        listings: list[Listing] = []161        for phase, civic in sorted(phases.items(), key=lambda kv: int(kv[0])):162            if phase in coming:163                continue164            listings.extend(self._parse_phase(phase, civic, prices))165        return listings166167    # -- page /phase-N : modèles groupés par typologie ---------------------------168    def _parse_phase(self, phase: str, civic: str,169                     prices: dict[str, float]) -> list[Listing]:170        url = f"{BASE}/phase-{phase}"171        try:172            soup = BeautifulSoup(self.get(url).text, "html.parser")173        except Exception:174            return []175        images = []176        for m in WIX_IMG_RE.finditer(str(soup)):177            full = f"https://static.wixstatic.com/media/{m.group(1)}"178            if full not in images:179                images.append(full)180        # parcours en ordre : un titre « 3 1/2 » ouvre une typologie, les181        # blocs « Unité A-03 · 104, 204... » qui suivent s'y rattachent182        typo = ""183        models: dict[str, list[str]] = {}184        for el in soup.select("h1, h2, h3, h4, h5"):185            t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))186            m = TYPO_RE.match(t)187            if m:188                typo = f"{m.group(1)}½"189                models.setdefault(typo, [])190                continue191            m = UNIT_RE.match(t)192            if m and typo:193                label = f"modèle {m.group(1)}"194                if m.group(2).strip():195                    label += f" (unités {m.group(2).strip()})"196                models[typo].append(label)197198        # nb d'unités de la phase (« Totalisant 28 unités locatives »)199        text = soup.get_text(" ", strip=True)200        m = re.search(r"(\d+)\s*unités", text)201        total = m.group(1) if m else ""202203        res: list[Listing] = []204        for typo, mods in models.items():205            if not mods:206                continue207            unit_type = normalize_unit_type(typo)208            price = prices.get(typo)209            desc = (f"Phase {phase} du Complexe St-Charles, {civic} "210                    f"{STREET} à {CITY}"211                    + (f" ({total} unités locatives)" if total else "") + ". "212                    f"Condos {typo} : " + " ; ".join(mods) + ".")213            res.append(Listing(214                source=self.source_id,215                external_id=f"phase-{phase}-{typo.replace('½', '.5')}",216                url=url,217                title=f"Complexe St-Charles — Phase {phase} — {typo}",218                address=f"{civic}, {STREET}",219                city=CITY,220                unit_type=unit_type,221                price=price,222                price_label=(f"à partir de {price:.0f} $ /mois"223                             if price else ""),224                description=desc[:1200],225                details={"phase": phase, "models": mods},226                images=images[:20],227            ))228        return res229
Files main
Menu

Theme