SPB Git

Repository Public

riocan.py 19.0 KB 454 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/riocan.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2713# Last Modified    : 2026-08-2714#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 (Québec + expansion Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/riocan.py : connecteur RioCan Living (riocanliving.com)91#   Bras résidentiel du REIT RioCan — tours locatives neuves au-dessus de ses92#   centres commerciaux (eCentral/ePlace et Pivot à Toronto, Rhythm à Ottawa,93#   Bridge à Leaside…). Le site corporatif est un WordPress SANS anti-bot :94#   CPT `property` exposé par l'API REST (`/wp-json/wp/v2/property?per_page=95#   100`) — on garde les billets EN (« /property/ » dans le lien, les billets96#   FR doublonnent sous « /fr/propriete/ »), de type « rental » et localisés97#   en Ontario (property-location-toronto-gta / -ottawa ; fourth-street-lofts98#   est à CALGARY -> exclu). La fiche riocanliving fournit adresse civique,99#   description, visuels app/uploads et le CTA « Website » vers le MICROSITE100#   de la tour — chaque tour a le sien, d'architecture différente :101#     - eCentral : blob JS `floorPlanData` (RentCafe embarqué : nom,102#       BedroomNum, BathNum, Size, MinimumRent, FloorplanId, avaliableDate)103#     - Pivot (livingatpivot.com, Cloudflare 403 -> la chaîne résiliente de104#       self.get escalade d'elle-même vers Scrapfly ASP) : cartes RentCafe105#       `.fp-container` (« N Bed / N Bath / N Sq. Ft. », « Starting at $X »,106#       « Available from JJ/MM/AAAA »)107#     - Bridge : cartes par CATÉGORIE (« Studio … Starting from $2,095* ») —108#       une annonce par catégorie de chambres, prix plancher affiché109#     - Rhythm : aucun prix publié -> repli « une annonce par propriété »110#   Fiche riocanliving + découverte du microsite via le cache BD111#   self.detail() (clé = date `modified` du flux WP) ; la page « suites » du112#   microsite est relue EN DIRECT à chaque synchronisation (donnée vivante).113#   Une annonce par plan d'étage TARIFÉ ; sinon par catégorie tarifée ; sinon114#   repli par propriété SANS prix (rien d'inventé).115#116#   Expansion Ontario — GATÉE par LOUKA_ONTARIO=1 : sans la variable, le117#   connecteur est `disabled` et exclu du registre (zéro impact prod QC).118# -----------------------------------------------------------------------------119from __future__ import annotations120121import os122import re123from urllib.parse import urljoin124125from bs4 import BeautifulSoup126127from ..schema import Listing, normalize_unit_type, parse_price128from .base import BaseConnector129130BASE = "https://riocanliving.com"131FEED_URL = f"{BASE}/wp-json/wp/v2/property?per_page=100"132133# Gate expansion Ontario : le connecteur reste hors registre tant que la134# variable d'environnement LOUKA_ONTARIO=1 n'est pas posée.135_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"136137# localisations ontariennes du CPT (class_list property-location-<slug>)138_ON_LOCATIONS = {"toronto-gta": "Toronto", "ottawa": "Ottawa"}139140# adresse civique sur la fiche (« 15 Roehampton Ave, Toronto, ON, M4P 1P9 »)141_ADDR_RE = re.compile(142    r"\d+[^,<>{}\n]{2,60},\s*[A-Za-z .'’-]+,\s*ON,?\s*"143    r"[A-Z]\d[A-Z]\s?\d[A-Z]\d")144# blob RentCafe embarqué (eCentral) : affectations JS, PAS du JSON —145# floorPlanData[0] = {name:'The Centric II', BedroomNum: '1', …};146_FPDATA_RE = re.compile(r"floorPlanData\[\d+\]\s*=\s*\{([\s\S]*?)\};")147# cartes par catégorie (Bridge) : « Studio Starting from $2,095* » —148# la catégorie doit être ADJACENTE au prix (pas de texte d'intro entre deux)149_CAT_RE = re.compile(150    r"(Studio|Bachelor|(\d+)[\s-]*Bed(?:room)?s?)\s*(?:\|\s*)?"151    r"Starting\s+from\s+\$\s*([\d,]+)", re.I)152_BED_RE = re.compile(r"(\d+)\s*Bed", re.I)153_BATH_RE = re.compile(r"([\d.]+)\s*Bath", re.I)154_SQFT_RE = re.compile(r"([\d,]+)\s*Sq\.?\s*Ft", re.I)155# lien « suites/plans » du microsite (découverte sur la page d'accueil)156_SUITES_HREF_RE = re.compile(157    r"(floor-?plans?|rental-suites|/suites?/?$|availability)", re.I)158159160class RioCanConnector(BaseConnector):161    source_id = "riocan"162    request_delay = 1.2       # microsites variés, dont un Cloudflare (Pivot)163    disabled = not _ONTARIO   # gate expansion Ontario (LOUKA_ONTARIO=1)164    max_properties = 10       # garde-fou (4 tours ON aujourd'hui)165    max_images = 15166167    def fetch(self) -> list[Listing]:168        props = self.get(FEED_URL,169                         headers={"Accept": "application/json"}).json()170171        listings: list[Listing] = []172        count = 0173        for p in props:174            try:175                link = p.get("link") or ""176                # billets EN seulement (les FR doublonnent /fr/propriete/)177                if "/property/" not in link:178                    continue179                cls = set(p.get("class_list") or [])180                if "property-type-rental" not in cls:181                    continue182                # Ontario seulement (fourth-street-lofts = Calgary -> exclu)183                city = ""184                for slug, label in _ON_LOCATIONS.items():185                    if f"property-location-{slug}" in cls:186                        city = label187                        break188                if not city:189                    continue190                if count >= self.max_properties:191                    break192                count += 1193                listings.extend(self._property_listings(p, city))194            except Exception:195                continue196        return listings197198    # -- annonces d'une tour (une par plan/catégorie tarifé, repli) -------------199    def _property_listings(self, p: dict, city: str) -> list[Listing]:200        pid = str(p.get("id"))201        link = p.get("link") or ""202        title = BeautifulSoup((p.get("title") or {}).get("rendered") or "",203                              "html.parser").get_text(" ", strip=True)204205        # fiche riocanliving + découverte du microsite via le cache BD :206        # revisitée seulement quand le billet WordPress est modifié207        feed_key = str(p.get("modified") or p.get("modified_gmt") or "")208        d = self.detail(pid, feed_key, lambda: self._fetch_detail(link))209210        url = d.get("microsite") or link211        common = dict(212            source=self.source_id, url=url,213            address=d.get("address") or "", city=city, province="ON",214            description=d.get("description") or "",215            images=(d.get("images") or [])[: self.max_images],216        )217218        # page « suites » du microsite EN DIRECT (prix/dispo = donnée vivante)219        page = ""220        suites_url = d.get("suites_url") or ""221        if suites_url:222            try:223                page = self.get(suites_url).text224            except Exception:225                page = ""226227        out = self._parse_floorplandata(page, pid, title, common)228        if not out:229            out = self._parse_fp_containers(page, pid, title, common)230        if not out:231            out = self._parse_categories(page, pid, title, common)232        if out:233            return out234235        # repli : une annonce par tour — aucun prix inventé (Rhythm…)236        return [Listing(237            external_id=pid,238            title=title,239            unit_type="",240            **common,241        )]242243    # -- parseur 1 : blob JS floorPlanData (eCentral) ----------------------------244    @staticmethod245    def _js_field(body: str, *keys: str) -> str:246        """Valeur d'un champ d'objet littéral JS (`name:'The Centric II'`)."""247        for k in keys:248            m = re.search(rf"\b{k}\s*:\s*'((?:[^'\\]|\\.)*)'", body)249            if m:250                return m.group(1).replace("\\'", "'").strip()251        return ""252253    def _parse_floorplandata(self, page: str, pid: str, title: str,254                             common: dict) -> list[Listing]:255        out: list[Listing] = []256        seen: set[str] = set()257        for m in _FPDATA_RE.finditer(page or ""):258            body = m.group(1)259            name = self._js_field(body, "name", "Name")260            fpid = self._js_field(body, "FloorplanId", "floorplanId", "id")261            key = fpid or re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")262            if not key or key in seen:263                continue264            seen.add(key)265            # loyer plancher affiché seulement (0/absent = pas de prix)266            price = None267            try:268                v = float(self._js_field(body, "MinimumRent")269                          .replace(",", "") or 0)270                if v > 0:271                    price = v272            except ValueError:273                pass274            if price is None:275                continue276            beds = baths = None277            try:278                beds = float(self._js_field(body, "BedroomNum"))279            except ValueError:280                pass281            try:282                baths = float(self._js_field(body, "BathNum", "Bath"))283            except ValueError:284                pass285            sqft = None286            msq = re.search(r"[\d,]+", self._js_field(body, "Size",287                                                      "DisplaySize"))288            if msq:289                try:290                    v = float(msq.group(0).replace(",", ""))291                    if 80 <= v <= 20000:292                        sqft = v293                except ValueError:294                    pass295            avail = self._js_field(body, "avaliableDate", "AvailableDate")296            out.append(Listing(297                external_id=f"{pid}-{key}",298                title=f"{title} — {name}" if name else title,299                unit_type=("Studio" if beds == 0 else normalize_unit_type(300                    f"{int(beds)} chambres") if beds is not None else ""),301                bedrooms=beds,302                bathrooms=baths,303                price=price,304                price_label=f"À partir de {price:.0f} $ /mois",305                availability=avail,306                area_sqft=sqft,307                **common,308            ))309        return out310311    # -- parseur 2 : cartes RentCafe .fp-container (Pivot) -----------------------312    def _parse_fp_containers(self, page: str, pid: str, title: str,313                             common: dict) -> list[Listing]:314        if not page or "fp-container" not in page:315            return []316        soup = BeautifulSoup(page, "html.parser")317        out: list[Listing] = []318        seen: set[str] = set()319        for card in soup.select("[id^=fp-container-]"):320            key = (card.get("id") or "").replace("fp-container-", "").strip()321            h = card.select_one(".card-title") or card.find(["h2", "h3"])322            name = h.get_text(" ", strip=True) if h else ""323            if not key:324                key = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")325            if not key or key in seen:326                continue327            seen.add(key)328            txt = card.get_text(" ", strip=True)329            # prix plancher affiché seulement (« Starting at $3,204.00 »)330            mprice = re.search(r"Starting\s+at\s+(\$[\d,.]+)", txt, re.I)331            price = parse_price(mprice.group(1)) if mprice else None332            if price is None:333                continue334            beds = None335            if re.search(r"\bStudio|\bBachelor", txt, re.I):336                beds = 0.0337            else:338                mb = _BED_RE.search(txt)339                if mb:340                    beds = float(mb.group(1))341            mba = _BATH_RE.search(txt)342            msq = _SQFT_RE.search(txt)343            sqft = float(msq.group(1).replace(",", "")) if msq else None344            mav = re.search(r"Available\s+from\s+([\d/]+)", txt, re.I)345            out.append(Listing(346                external_id=f"{pid}-{key}",347                title=f"{title} — {name}" if name else title,348                unit_type=("Studio" if beds == 0 else normalize_unit_type(349                    f"{int(beds)} chambres") if beds is not None else ""),350                bedrooms=beds,351                bathrooms=float(mba.group(1)) if mba else None,352                price=price,353                price_label=f"À partir de {price:.0f} $ /mois",354                availability=f"Disponible le {mav.group(1)}" if mav else "",355                area_sqft=sqft if sqft and 80 <= sqft <= 20000 else None,356                **common,357            ))358        return out359360    # -- parseur 3 : cartes par catégorie (Bridge) --------------------------------361    def _parse_categories(self, page: str, pid: str, title: str,362                          common: dict) -> list[Listing]:363        if not page:364            return []365        txt = BeautifulSoup(page, "html.parser").get_text(" ", strip=True)366        out: list[Listing] = []367        seen: set[str] = set()368        for m in _CAT_RE.finditer(txt):369            label = m.group(1).strip()370            beds = 0.0 if m.group(2) is None else float(m.group(2))371            key = "studio" if beds == 0 else f"{int(beds)}-bed"372            if key in seen:373                continue374            seen.add(key)375            try:376                price = float(m.group(3).replace(",", ""))377            except ValueError:378                continue379            if price <= 0:380                continue381            out.append(Listing(382                external_id=f"{pid}-cat-{key}",383                title=f"{title} — {label}",384                unit_type=("Studio" if beds == 0385                           else normalize_unit_type(f"{int(beds)} chambres")),386                bedrooms=beds,387                price=price,388                price_label=f"À partir de {price:.0f} $ /mois",389                **common,390            ))391        return out392393    # -- fiche riocanliving : adresse, description, visuels, microsite -----------394    def _fetch_detail(self, link: str) -> dict:395        out: dict = {"address": "", "description": "", "images": [],396                     "microsite": "", "suites_url": ""}397        if not link:398            return out399        try:400            page = self.get(link).text401        except Exception:402            return out403        soup = BeautifulSoup(page, "html.parser")404405        m = _ADDR_RE.search(soup.get_text(" ", strip=True))406        if m:407            out["address"] = re.sub(r"\s+", " ", m.group(0)).strip()408409        # description : premiers paragraphes substantiels de la fiche410        paras = [q.get_text(" ", strip=True) for q in soup.find_all("p")]411        out["description"] = " ".join(412            t for t in paras if len(t) > 60)[:600]413414        # visuels du site corporatif (app/uploads) — hors logos/icônes415        images: list[str] = []416        for img in soup.find_all("img"):417            src = (img.get("src") or "").strip()418            if "/app/uploads/" not in src or src.lower().endswith(".svg"):419                continue420            if re.search(r"logo|icon", src, re.I):421                continue422            if src not in images:423                images.append(src)424        out["images"] = images[: self.max_images]425426        # CTA « Website » -> microsite de la tour427        micro = ""428        for a in soup.find_all("a", href=True):429            if a.get_text(" ", strip=True).lower() in (430                    "website", "visit website"):431                micro = a["href"].strip()432                break433        out["microsite"] = micro434        if not micro:435            return out436437        # découverte de la page « suites/plans » sur l'accueil du microsite438        # (la chaîne résiliente escalade seule le Cloudflare de Pivot)439        try:440            home = self.get(micro).text441        except Exception:442            return out443        hsoup = BeautifulSoup(home, "html.parser")444        for a in hsoup.find_all("a", href=True):445            href = a["href"].strip()446            if _SUITES_HREF_RE.search(href.split("?")[0]):447                out["suites_url"] = urljoin(micro, href)448                break449        # certains microsites affichent les plans sur l'accueil même450        if not out["suites_url"] and (451                "floorPlanData" in home or "fp-container" in home):452            out["suites_url"] = micro453        return out454
Files main
Menu

Theme