SPB Git

Repository Public

greenrock.py 16.9 KB 407 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/greenrock.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/greenrock.py : connecteur Greenrock (Davisville Village, Toronto)91#   IMPASSE VÉRIFIÉE 2026-08-27 sur les sites Greenrock eux-mêmes :92#     - greenrock.ca : NXDOMAIN (n'existe plus) ;93#     - greenrockrsca.com (ancien site locatif Rentsync, vivant encore le94#       2026-06-13 d'après la Wayback Machine) : 522 Cloudflare persistant,95#       origine décommissionnée ; sa clé de passerelle Rentsync `greenrock`96#       répond encore mais avec 0 propriété (portefeuille vidé) ;97#     - Village Green (40/50 Alexander, 55 Maitland…) : VENDU — désormais98#       commercialisé par Brookfield Properties (hors périmètre de ce fichier).99#   Ce qui RESTE à Greenrock (greenrockreal.ca, « Greenrock Portfolio ») :100#   Davisville Village à Toronto — 45 Balliol Street, 225 Davisville Avenue,101#   Balliol & Davisville Townhomes (226-228 Balliol n'a pas de page locative).102#   Ces immeubles sont maintenant GÉRÉS/AFFICHÉS PAR STERLING KARAMAR : on103#   les lit sur la passerelle JSON publique Rentsync nouvelle génération104#   `website-gateway-cdn.rentsync.com/v1/sterlingkaramar/…` (zéro auth, zéro105#   anti-bot — même mécanique que skyline.py), STRICTEMENT limités au106#   portefeuille Greenrock par une liste blanche d'importId Yardi stables107#   (yardi:ball0045, yardi:davi0225, yardi:davi0207). Une annonce par type108#   d'unité disponible (rangées /units regroupées par plan, loyer plancher).109#   ⚠️ Si un connecteur Sterling Karamar complet est écrit un jour (216+110#   immeubles sur la même passerelle, suite notée dans project_ontario.md),111#   retirer ce fichier ou y exclure ces trois importId pour éviter le doublon.112#   Expansion Ontario — gaté LOUKA_ONTARIO=1 : sans la variable, disabled.113# -----------------------------------------------------------------------------114from __future__ import annotations115116import html as htmllib117import os118import re119120from bs4 import BeautifulSoup121122from ..schema import Listing, normalize_unit_type, strip_accents123from .base import BaseConnector124125SITE = "https://www.sterlingkaramar.com"126GATEWAY = "https://website-gateway-cdn.rentsync.com/v1/sterlingkaramar"127IMG_BASE = ("https://s3.amazonaws.com/lws_lift/sterlingkaramar/images/"128            "gallery/full")129130# Gate expansion Ontario : hors registre tant que LOUKA_ONTARIO=1 absent131_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"132133# Portefeuille Greenrock (greenrockreal.ca) sur la passerelle Sterling134# Karamar : identifiants d'import Yardi (stables, contrairement aux ids)135_GREENROCK_IMPORT_IDS = {136    "yardi:ball0045",   # 45 Balliol Street137    "yardi:davi0225",   # 225 Davisville Avenue138    "yardi:davi0207",   # Balliol & Davisville Townhomes139}140141_ISO_DATE_RE = re.compile(r"^20\d{2}-\d{2}-\d{2}")142_COUNTY_RE = re.compile(r"\b(county|region|district|municipality)\b", re.I)143144145class GreenrockConnector(BaseConnector):146    source_id = "greenrock"147    request_delay = 1.0148    disabled = not _ONTARIO          # gate Ontario (voir en-tête)149    max_properties = 10              # garde-fou (3 immeubles au 2026-08)150    max_listings = 100               # garde-fou global (20 rangées au 2026-08)151    max_images = 15152    page_limit = 200153154    # -- accès passerelle ---------------------------------------------------------155    def _get_json(self, path: str, params: dict) -> dict:156        resp = self.get(GATEWAY + path, params=params, headers={157            "Accept": "application/json",158            "Origin": SITE,159            "Referer": SITE + "/",160            "rs-lang": "en",161        })162        return resp.json()163164    def _paged(self, path: str, params: dict, max_pages: int = 5) -> list[dict]:165        out: list[dict] = []166        page = 1167        while page <= max_pages:168            data = self._get_json(path, {**params, "page": page})169            out.extend(data.get("data") or [])170            meta = data.get("meta") or {}171            if page >= int(meta.get("totalPages") or 1):172                break173            page += 1174        return out175176    # -- collecte -----------------------------------------------------------------177    def fetch(self) -> list[Listing]:178        # immeubles du portefeuille Greenrock seulement (liste blanche)179        props = [p for p in self._paged("/properties",180                                        {"limit": self.page_limit})181                 if (p.get("importId") or "").strip()182                 in _GREENROCK_IMPORT_IDS][: self.max_properties]183        if not props:184            return []185        by_id = {int(p["id"]): p for p in props}186        ids = "|".join(str(i) for i in sorted(by_id))187188        # villes -> nom + garde-fou provincial (Toronto ON attendu)189        cities: dict[int, tuple[str, str]] = {}190        for c in self._paged("/cities", {191            "where": "id~in:" + "|".join(192                sorted({str(p.get("cityId")) for p in props193                        if p.get("cityId")})),194            "relations": "province:p",195            "limit": self.page_limit,196        }):197            prov = c.get("province") or {}198            cities[int(c["id"])] = (199                (c.get("cityName") or "").strip(),200                (prov.get("provinceCode") or "").strip().upper())201202        # rangées d'unités disponibles des seuls immeubles Greenrock,203        # regroupées par (immeuble, plan, cc, sdb) = une annonce par type204        units = self._paged("/units", {205            "where": f"status:enabled,available~in:1,buildingId~in:{ids}",206            "limit": self.page_limit,207        })208        by_building: dict[int, dict[tuple, list[dict]]] = {}209        for u in units:210            bid = int(u.get("buildingId") or 0)211            if bid not in by_id:212                continue213            key = ((u.get("typeName") or "").strip().lower(),214                   u.get("bedMin", u.get("bed")),215                   u.get("bathMin", u.get("bath")))216            by_building.setdefault(bid, {}).setdefault(key, []).append(u)217218        # galeries photo par immeuble219        photos: dict[int, list[str]] = {}220        try:221            for ph in self._paged("/photos", {222                "relations": "buildingsHasPhotos:bhp",223                "where": f"bhp.buildingId~in:{ids}",224                "orderBy": "bhp.orderBy~asc",225                "limit": self.page_limit,226            }):227                bid, img = ph.get("buildingId"), (ph.get("image") or "").strip()228                if not bid or not img:229                    continue230                urls = photos.setdefault(int(bid), [])231                u = f"{IMG_BASE}/{img}"232                if len(urls) < self.max_images and u not in urls:233                    urls.append(u)234        except Exception:235            pass    # galerie manquante : annonces sans photo plutôt que rien236237        listings: list[Listing] = []238        for bid, groups in by_building.items():239            p = by_id[bid]240            city, prov = cities.get(int(p.get("cityId") or 0), ("", ""))241            if prov != "ON" or not city:242                continue243            try:244                base = self._building_ctx(p, city, photos.get(bid) or [])245            except Exception:246                continue247            for rows in groups.values():248                if len(listings) >= self.max_listings:249                    break250                try:251                    listings.append(self._listing(bid, rows, base))252                except Exception:253                    continue254        return listings255256    # -- contexte immeuble (partagé entre ses annonces) -----------------------------257    def _building_ctx(self, p: dict, city: str, images: list[str]) -> dict:258        street = " ".join(x for x in (259            (p.get("streetNumber") or "").strip(),260            (p.get("streetName") or "").strip()) if x)261        postal = (p.get("postal") or "").strip()262        address = ", ".join(x for x in (street, city) if x)263        if address:264            address += f", ON {postal}".rstrip()265266        sector = (p.get("neighbourhood") or "").strip()267        if not sector or _COUNTY_RE.search(sector):268            sector = "Davisville Village"   # quartier réel du portefeuille269270        try:271            lat = float(p["latitude"]) if p.get("latitude") else None272            lng = float(p["longitude"]) if p.get("longitude") else None273        except (TypeError, ValueError):274            lat = lng = None275276        amenities: list[str] = []277        feats = htmllib.unescape(p.get("buildingFeatures") or "")278        for li in BeautifulSoup(feats, "html.parser").find_all("li"):279            t = li.get_text(" ", strip=True)280            if t and t not in amenities:281                amenities.append(t)282283        desc_html = (p.get("buildingOverview") or "") + " " + \284                    (p.get("suiteDetails") or "")285        desc = BeautifulSoup(htmllib.unescape(desc_html),286                             "html.parser").get_text(" ", strip=True)287288        pets = None289        if p.get("petsNotAllowed") == 1:290            pets = "non"291        elif p.get("petFriendly") == 1:292            pets = "oui"293294        details: dict = {"Gestion": "Sterling Karamar (portefeuille Greenrock)"}295        contact: dict = {}296        if (p.get("phone") or "").strip():297            contact["phone"] = p["phone"].strip()298        email = (p.get("email") or "").split(",")[0].strip()299        if email:300            contact["email"] = email301        if contact:302            details["contact"] = contact303        try:304            if int(p.get("yearBuilt") or 0) > 1800:305                details["Année de construction"] = int(p["yearBuilt"])306            if int(p.get("floorCount") or 0) > 0:307                details["Étages"] = int(p["floorCount"])308        except (TypeError, ValueError):309            pass310311        perma = (p.get("fullPermaLink") or "").strip().strip("/")312        url = f"{SITE}/{perma}" if perma else SITE313314        return {"city": city, "address": address, "sector": sector,315                "lat": lat, "lng": lng, "amenities": amenities, "desc": desc,316                "pets": pets, "details": details, "url": url,317                "images": images[: self.max_images],318                "name": htmllib.unescape((p.get("buildingName") or "")319                                         .strip())}320321    # -- une annonce par type d'unité disponible (rangées regroupées) ---------------322    def _listing(self, bid: int, rows: list[dict], b: dict) -> Listing:323        u = rows[0]324        type_name = (u.get("typeName") or "").strip()325        unit_type = normalize_unit_type(type_name)326        bed = u.get("bedMin", u.get("bed"))327        bath = u.get("bathMin", u.get("bath"))328        if bed is not None and (not unit_type or unit_type == type_name):329            unit_type = ("Studio" if int(bed) == 0330                         else normalize_unit_type(f"{int(bed)} chambres"))331332        # loyer : plancher du groupe (masqué si hideRateWebsites=1)333        rates: list[float] = []334        for r in rows:335            if r.get("hideRateWebsites"):336                continue337            try:338                lo = float(r.get("rateMin") or r.get("rate") or 0)339                hi = float(r.get("rateMax") or lo)340            except (TypeError, ValueError):341                continue342            if lo > 0:343                rates += [lo, max(hi, lo)]344        price = min(rates) if rates else None345        price_label = ""346        if price is not None:347            price_label = (f"À partir de {price:.0f} $" if max(rates) > price348                           else f"{price:.0f} $ /mois")349350        # superficie plancher plausible (le flux publie parfois 0)351        area = None352        for r in rows:353            try:354                v = float(r.get("sqFtMin") or r.get("sqFt") or 0)355            except (TypeError, ValueError):356                continue357            if 80 <= v <= 20000 and (area is None or v < area):358                area = v359360        dates = sorted(str(r.get("availabilityDate") or "").strip()[:10]361                       for r in rows362                       if _ISO_DATE_RE.match(str(r.get("availabilityDate")363                                                  or "")))364        avail_date = dates[0] if dates else None365        availability = f"Disponible le {avail_date}" if avail_date \366            else "Disponible"367        if len(rows) > 1:368            availability += f" — {len(rows)} unités"369370        details = dict(b["details"])371        if (u.get("leaseTerm") or "").strip():372            details["Bail"] = u["leaseTerm"].strip()373374        slug = re.sub(r"[^a-z0-9]+", "-",375                      strip_accents(type_name.lower())).strip("-")376        ext = f"{bid}-{slug or 'u'}"377        if bed is not None or bath is not None:378            ext += f"-{bed}-{bath}"379380        return Listing(381            source=self.source_id,382            external_id=ext,383            url=b["url"],384            title=f"{b['name']} — {type_name}" if type_name else b["name"],385            address=b["address"],386            sector=b["sector"],387            city=b["city"],388            province="ON",389            unit_type=unit_type,390            bedrooms=float(bed) if bed is not None else None,391            bathrooms=float(bath) if bath else None,392            price=price,393            price_label=price_label,394            availability=availability,395            availability_date=avail_date,396            area_sqft=area,397            pets=b["pets"],398            furnished=True if rows and all(r.get("furnished") == 1399                                           for r in rows) else None,400            description=b["desc"][:600],401            amenities=b["amenities"][:25],402            details=details,403            images=b["images"],404            lat=b["lat"],405            lng=b["lng"],406        )407
Files main
Menu

Theme