SPB Git

Repository Public

brivia_1sp.py 15.0 KB 354 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/brivia_1sp.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/brivia_1sp.py : connecteur 1 Square Phillips (Groupe Brivia)91#   (1squarephillips.ca/locatif — tour locative au centre-ville de Montréal,92#    1205 rue du Square-Phillips, Ville-Marie). La page /locatif présente les93#    trois typologies offertes (Studio / 1 Chambre / 2 Chambres) avec loyer94#    "à partir de" -> une annonce par typologie (uid stables). L'inventaire95#    unité par unité est exposé par l'API AJAX des plans (2022/php/96#    ajax_load_unit_selector/_floor/_unit.php, phase=rental) : on y lit les97#    unités réellement disponibles (« onsale »), leur étage, leur superficie98#    (pi²) et le plan — utilisés pour enrichir chaque typologie.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103import time104105from bs4 import BeautifulSoup106107from ..schema import Listing, parse_price108from .base import BaseConnector109110BASE = "https://www.1squarephillips.ca"111LOCATIF_URL = f"{BASE}/locatif"112GALERIE_URL = f"{BASE}/galerie"113PLANS_AJAX = f"{BASE}/2022/php/"114115# Adresse du pied de page (avec code postal)116ADDRESS = "1205, rue du Square-Phillips, Montréal, QC H3B 3C9"117118_TYPE_MAP = {"studio": "Studio", "1 chambre": "3½", "2 chambres": "4½",119             "3 chambres": "5½"}120# Typologie -> data-type de l'API des plans (phase locative)121_PLAN_TYPE = {"studio": 11, "1 chambre": 12, "2 chambres": 13}122123DESCRIPTION = ("Condos locatifs de luxe au centre-ville de Montréal, formule "124               "tout inclus : électroménagers, climatisation, chauffage, "125               "électricité, eau chaude et Wi-Fi.")126127# Repli si la section « Caractéristiques » du site devenait illisible128AMENITIES = ["Tout inclus (électricité, chauffage, climatisation, eau chaude, "129             "Wi-Fi)", "Électroménagers inclus", "Piscine, sauna et bain "130             "vapeur", "Salles d'entraînement", "Espace de cotravail",131             "Salle de cinéma", "Terrasse", "Gardien 24 h", "Lounge du 21e "132             "étage", "Stationnement souterrain"]133134_ONSALE_RE = re.compile(r'id="unit(\d+)" class="unit onsale"')135_FLOOR_RE = re.compile(r'data-floor="(\d+)"')136_AREA_RE = re.compile(r"Superficie\s*</span><span>([\d\s  ,]+)\s*pi", re.I)137_BALCONY_RE = re.compile(r"Balcon\s*</span><span>([\d\s  ,]+)\s*pi", re.I)138139140def _unit_type(label: str) -> str:141    key = re.sub(r"\s+", " ", (label or "").strip().lower())142    return _TYPE_MAP.get(key, label.strip())143144145def _num(txt: str) -> float | None:146    try:147        return float(re.sub(r"[\s  ,]", "", txt))148    except (TypeError, ValueError):149        return None150151152class Brivia1SPConnector(BaseConnector):153    source_id = "brivia_1sp"154    request_delay = 0.6155    max_unit_details = 150   # plafond de fiches unité par sync156157    # -- helpers ---------------------------------------------------------------158    def _post_json(self, path: str, data: dict) -> dict:159        """POST throttlé vers l'API AJAX des plans (réponses JSON)."""160        wait = self.request_delay - (time.time() - self._last_request)161        if wait > 0:162            time.sleep(wait)163        resp = self.session.post(PLANS_AJAX + path, data=data,164                                 timeout=self.timeout)165        self._last_request = time.time()166        resp.raise_for_status()167        return resp.json()168169    def _fetch_unit(self, unit: str) -> dict:170        """Fiche d'une unité (type, étage, superficie, plan) via l'API."""171        d = self._post_json("ajax_load_plans_unit.php",172                            {"lang": "fr", "phase": "rental", "unit": unit})173        html = d.get("unit_details") or ""174        out: dict = {"unit": unit, "type": int(d.get("type") or 0),175                     "floor": int(d.get("floor") or 0)}176        m = _AREA_RE.search(html)177        if m:178            out["area_sqft"] = _num(m.group(1))179        m = _BALCONY_RE.search(html)180        if m:181            out["balcony_sqft"] = _num(m.group(1))182        # « 1 chambre / 1 salle de bain »183        m = re.search(r'<p class="uppercase">([^<]+)</p>', html)184        if m:185            out["rooms"] = m.group(1).strip()186        m = re.search(r"<h3>\s*Plan\s*([^<]+)</h3>", html)187        if m:188            out["plan"] = m.group(1).strip()189        m = re.search(r'<img src="([^"]+)"', d.get("unit_plan") or "")190        if m:191            out["plan_img"] = m.group(1)192        return out193194    def _rental_units(self) -> dict[int, list[dict]]:195        """Unités disponibles (« onsale ») par type (11/12/13), via l'API."""196        sel = self._post_json("ajax_load_unit_selector.php",197                              {"lang": "fr", "phase": "rental"})198        floors = sorted({int(f) for f in199                         _FLOOR_RE.findall(sel.get("unit_selector") or "")})200        onsale: list[str] = []201        for f in floors[:40]:202            d = self._post_json("ajax_load_plans_floor.php",203                                {"lang": "fr", "phase": "rental",204                                 "type": 11, "floor": f})205            onsale.extend(_ONSALE_RE.findall(d.get("floor") or ""))206        by_type: dict[int, list[dict]] = {}207        for u in onsale[: self.max_unit_details]:208            # la fiche d'une unité (plan) est immuable -> clé de cache fixe209            info = self.detail(f"unit-{u}", "plan-v1",210                               lambda u=u: self._fetch_unit(u))211            if info.get("unit"):212                by_type.setdefault(int(info.get("type") or 0), []).append(info)213        return by_type214215    # -- fetch -----------------------------------------------------------------216    def fetch(self) -> list[Listing]:217        listings: list[Listing] = []218        try:219            html = self.get(LOCATIF_URL).text220        except Exception:221            return listings222        soup = BeautifulSoup(html, "html.parser")223224        # Photos : perspectives de la page locatif + galerie du site225        images = self._collect_images(html)226        try:227            images += self._collect_images(self.get(GALERIE_URL).text)228        except Exception:229            pass230        images = list(dict.fromkeys(images))[:30]231232        # Caractéristiques réelles de l'immeuble (section .features)233        amenities = self._collect_features(soup) or list(AMENITIES)234235        # Contact structuré (liens tel:/mailto: du pied de page)236        contact: dict = {}237        tel = soup.select_one('a[href^="tel:"]')238        if tel:239            digits = re.sub(r"\D", "", tel["href"])[-10:]240            if len(digits) == 10:241                contact["phone"] = f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"242        mail = soup.select_one('a[href^="mailto:"]')243        if mail:244            contact["email"] = mail["href"].removeprefix("mailto:").strip()245246        # Inventaire unité par unité (API AJAX des plans, phase locative)247        inventory: dict[int, list[dict]] = {}248        try:249            inventory = self._rental_units()250        except Exception:251            pass252253        # Typologies (ul.grid3cols : h4 = type, p = "à partir de X $/mois")254        for li in soup.select("ul.grid3cols li"):255            try:256                h4 = li.select_one("h4")257                p = li.select_one("p")258                if not h4 or not p:259                    continue260                typology = h4.get_text(" ", strip=True).replace("\xa0", " ")261                price_label = re.sub(r"\s+", " ",262                                     p.get_text(" ", strip=True))263                if "$" not in price_label:264                    continue265                type_slug = re.sub(r"[^a-z0-9]+", "-",266                                   typology.lower()).strip("-")267268                # Enrichissement avec les unités disponibles de la typologie269                tkey = re.sub(r"\s+", " ", typology.strip().lower())270                units = sorted(inventory.get(_PLAN_TYPE.get(tkey, -1), []),271                               key=lambda u: u["unit"])272                availability = "Disponible (tour locative en location)"273                description = DESCRIPTION274                area = None275                unit_images: list[str] = []276                if units:277                    n = len(units)278                    availability = (f"{n} unité{'s' if n > 1 else ''} "279                                    f"disponible{'s' if n > 1 else ''}")280                    areas = [u["area_sqft"] for u in units281                             if u.get("area_sqft")]282                    area = min(areas) if areas else None283                    # nota : pas de mention « étage N » ici, sinon la284                    # normalisation centrale déduirait un faux details.floor285                    dispo = ", ".join(286                        f"unité {u['unit']}"287                        + (f" ({u['area_sqft']:.0f} pi²"288                           + (f" + balcon {u['balcony_sqft']:.0f} pi²"289                              if u.get("balcony_sqft") else "") + ")"290                           if u.get("area_sqft") else "")291                        for u in units)292                    description = f"{DESCRIPTION} Unités disponibles : {dispo}."293                    unit_images = [u["plan_img"] for u in units294                                   if u.get("plan_img")]295296                details: dict = {}297                if contact:298                    details["contact"] = dict(contact)299300                listings.append(Listing(301                    source=self.source_id,302                    external_id=f"1sp-{type_slug}",303                    url=LOCATIF_URL,304                    title=f"1 Square Phillips — {typology} locatif",305                    address=ADDRESS,306                    sector="Centre-ville (Ville-Marie)",307                    city="Montréal",308                    unit_type=_unit_type(typology),309                    price=parse_price(price_label),310                    price_label=price_label,311                    availability=availability,312                    area_sqft=area,313                    description=description,314                    amenities=amenities,315                    details=details,316                    images=list(dict.fromkeys(unit_images + images))[:40],317                ))318            except Exception:319                continue320        return listings321322    @staticmethod323    def _collect_features(soup: BeautifulSoup) -> list[str]:324        """Caractéristiques de l'immeuble (section .features, div.back)."""325        out: list[str] = []326        for el in soup.select("section.features li div.back"):327            t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))328            if t and t not in out:329                out.append(t)330        if out:331            # inclusions énoncées dans l'intro de la page locatif332            out.insert(0, "Tout inclus (électricité, chauffage, climatisation, "333                          "eau chaude, Wi-Fi)")334            out.insert(1, "Électroménagers inclus")335        return out[:40]336337    @staticmethod338    def _collect_images(html: str) -> list[str]:339        """Images pleine taille du site (perspectives + galerie)."""340        urls = re.findall(341            r'(?:https://www\.1squarephillips\.ca)?/?2022/images/'342            r'[^"\'\s\)]+\.(?:jpg|jpeg|png|webp)', html)343        out = []344        for u in urls:345            if not u.startswith("http"):346                u = f"{BASE}/{u.lstrip('/')}"347            # exclure variantes portrait (doublons) et visuels non pertinents348            if re.search(r"-portrait\.|ico-|logo|favicon|bckg-contact|"349                         r"bckg-project-(1|4)\b", u, re.I):350                continue351            if re.search(r"gallery|rental|persp|condo", u, re.I):352                out.append(u)353        return list(dict.fromkeys(out))354
Files main
Menu

Theme