SPB Git

Repository Public

skyline.py 18.0 KB 426 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/skyline.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 (province de Québec + Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/skyline.py : connecteur Skyline Living (skylineliving.ca)91#   Gestionnaire clé des villes secondaires ontariennes (~22 000 unités,92#   ~38 villes : Guelph HQ, Est ontarien, Niagara, Sud-Ouest, Nord, Centre).93#   Le site est une SPA Rentsync « nouvelle génération » : ses bundles94#   (cdn.rentsync.com/site/skyline) appellent la passerelle JSON publique95#   `https://website-gateway-cdn.rentsync.com/v1/skyline/…` (aucun jeton,96#   le UA de base passe). Endpoints utilisés :97#     - /properties?limit=1000 — tous les immeubles actifs (~193) : adresse,98#       lat/lng, cityId, description, caractéristiques, animaux, contact ;99#     - /cities?where=id~in:…&relations=province:p — nom de ville + province100#       (filtre ON strict : Skyline a aussi quelques immeubles hors Ontario) ;101#     - /units?where=status:enabled,available~in:1 — types d'unités avec102#       vacance (loyer, cc/sdb, pi², date), paginés (meta.totalPages) ;103#     - /photos?relations=buildingsHasPhotos:bhp&where=bhp.buildingId~in:… —104#       galeries par lots d'immeubles (images S3 lws_lift, taille « full »).105#   Une annonce par type d'unité disponible (comme capreit). NB : dans les106#   tours neuves en location (ex. Sky Towers à Barrie), le flux publie UNE107#   rangée PAR APPARTEMENT (champ `number`) du même plan — on regroupe donc108#   par (immeuble, typeName, cc, sdb) : loyer plancher « à partir de »,109#   date la plus proche, identifiant stable immeuble+plan. Tout vient de110#   l'API par lots (~15 requêtes au total) : aucune page détail à visiter,111#   donc pas besoin du cache BD self.detail().112#   Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : sans la variable, le113#   connecteur est `disabled` (exclu du registre), prod QC inchangée.114#   NB : le parc Thunder Bay a été vendu (2025-2026) — absent du flux, normal.115# -----------------------------------------------------------------------------116from __future__ import annotations117118import html as htmllib119import os120import re121122from bs4 import BeautifulSoup123124from ..schema import Listing, normalize_unit_type, strip_accents125126from .base import BaseConnector127128BASE = "https://www.skylineliving.ca"129GATEWAY = "https://website-gateway-cdn.rentsync.com/v1/skyline"130IMG_BASE = "https://s3.amazonaws.com/lws_lift/skyline/images/gallery/full"131132# Expansion Ontario 2026-08 — gate : sans LOUKA_ONTARIO=1, connecteur inactif133_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"134135# secteur : le champ `neighbourhood` du flux contient souvent le comté136# (« Grey County », « Niagara Region ») — pas un quartier, on l'écarte137_COUNTY_RE = re.compile(r"\b(county|region|district|municipality)\b", re.I)138_ISO_DATE_RE = re.compile(r"^20\d{2}-\d{2}-\d{2}")139140141class SkylineConnector(BaseConnector):142    source_id = "skyline"143    request_delay = 0.8144    disabled = not _ONTARIO          # gate Ontario (voir en-tête)145    max_properties = 250             # garde-fou immeubles (193 au 2026-08)146    max_listings = 1500              # garde-fou global (≈480 groupes au 2026-08)147    max_images = 15148    page_limit = 750                 # taille de page maximale de la passerelle149    photo_chunk = 40                 # immeubles par requête /photos150151    # -- accès passerelle -------------------------------------------------------152    def _get_json(self, path: str, params: dict) -> dict:153        resp = self.get(GATEWAY + path, params=params, headers={154            "Accept": "application/json",155            "Origin": BASE,156            "Referer": BASE + "/",157            "rs-lang": "en",158        })159        return resp.json()160161    def _paged(self, path: str, params: dict, max_pages: int = 10) -> list[dict]:162        """Concatène toutes les pages d'un endpoint (meta.totalPages)."""163        out: list[dict] = []164        page = 1165        while page <= max_pages:166            data = self._get_json(path, {**params, "page": page})167            out.extend(data.get("data") or [])168            meta = data.get("meta") or {}169            if page >= int(meta.get("totalPages") or 1):170                break171            page += 1172        return out173174    # -- villes : cityId -> (nom, code province) --------------------------------175    def _cities(self, city_ids: set[int]) -> dict[int, tuple[str, str]]:176        ids = "|".join(str(i) for i in sorted(city_ids))177        rows = self._paged("/cities", {178            "where": f"id~in:{ids}",179            "relations": "province:p",180            "limit": self.page_limit,181        })182        out: dict[int, tuple[str, str]] = {}183        for c in rows:184            prov = c.get("province") or {}185            out[int(c["id"])] = ((c.get("cityName") or "").strip(),186                                 (prov.get("provinceCode") or "").strip().upper())187        return out188189    # -- galeries photo par lots d'immeubles ------------------------------------190    def _photos(self, building_ids: list[int]) -> dict[int, list[str]]:191        out: dict[int, list[str]] = {}192        for i in range(0, len(building_ids), self.photo_chunk):193            chunk = building_ids[i:i + self.photo_chunk]194            ids = "|".join(str(b) for b in chunk)195            try:196                rows = self._paged("/photos", {197                    "relations": "buildingsHasPhotos:bhp",198                    "where": f"bhp.buildingId~in:{ids}",199                    "orderBy": "bhp.orderBy~asc",200                    "limit": self.page_limit,201                })202            except Exception:203                continue    # galerie manquante : annonces sans photo plutôt que rien204            for ph in rows:205                bid = ph.get("buildingId")206                img = (ph.get("image") or "").strip()207                if not bid or not img:208                    continue209                urls = out.setdefault(int(bid), [])210                if len(urls) < self.max_images:211                    u = f"{IMG_BASE}/{img}"212                    if u not in urls:213                        urls.append(u)214        return out215216    # -- collecte ---------------------------------------------------------------217    def fetch(self) -> list[Listing]:218        props = self._paged("/properties", {"limit": 1000})[: self.max_properties]219220        # villes -> filtre Ontario strict (le flux a quelques immeubles hors ON)221        cities = self._cities({int(p["cityId"]) for p in props if p.get("cityId")})222        on_props: dict[int, dict] = {}223        for p in props:224            name, prov = cities.get(int(p.get("cityId") or 0), ("", ""))225            if prov != "ON" or not name:226                continue227            p["_city"] = name228            on_props[int(p["id"])] = p229230        # types d'unités avec vacance : dans les tours en location, le flux231        # publie une rangée PAR APPARTEMENT du même plan — regrouper par232        # (immeuble, plan, cc, sdb) pour une annonce par type d'unité233        units = self._paged("/units", {234            "where": "status:enabled,available~in:1",235            "limit": self.page_limit,236        })237        by_building: dict[int, dict[tuple, list[dict]]] = {}238        for u in units:239            bid = int(u.get("buildingId") or 0)240            if bid not in on_props:241                continue242            key = ((u.get("typeName") or "").strip().lower(),243                   u.get("bedMin", u.get("bed")),244                   u.get("bathMin", u.get("bath")))245            by_building.setdefault(bid, {}).setdefault(key, []).append(u)246247        # galeries des seuls immeubles qui produisent des annonces248        photos = self._photos(sorted(by_building))249250        listings: list[Listing] = []251        for bid, groups in by_building.items():252            if len(listings) >= self.max_listings:253                break254            p = on_props[bid]255            try:256                base = self._building_ctx(p, photos.get(bid) or [])257            except Exception:258                continue259            for rows in groups.values():260                if len(listings) >= self.max_listings:261                    break262                try:263                    listings.append(self._listing(bid, rows, base))264                except Exception:265                    continue266        return listings267268    # -- contexte immeuble (partagé entre ses annonces) --------------------------269    def _building_ctx(self, p: dict, images: list[str]) -> dict:270        city = p["_city"]271        street = " ".join(x for x in (272            (p.get("streetNumber") or "").strip(),273            (p.get("streetName") or "").strip()) if x)274        postal = (p.get("postal") or "").strip()275        address = ", ".join(x for x in (street, city) if x)276        if address:277            address += f", ON {postal}".rstrip()278279        # secteur : quartier seulement (écarter comtés/« regions » du flux)280        sector = (p.get("neighbourhood") or "").strip()281        if _COUNTY_RE.search(sector):282            sector = ""283284        try:285            lat = float(p["latitude"]) if p.get("latitude") else None286            lng = float(p["longitude"]) if p.get("longitude") else None287        except (TypeError, ValueError):288            lat = lng = None289290        # caractéristiques de l'immeuble : HTML doublement échappé dans le flux291        amenities: list[str] = []292        feats = htmllib.unescape(p.get("buildingFeatures") or "")293        for li in BeautifulSoup(feats, "html.parser").find_all("li"):294            t = li.get_text(" ", strip=True)295            if t and t not in amenities:296                amenities.append(t)297298        # description : aperçu de l'immeuble (+ détails des suites si présents)299        desc_html = (p.get("buildingOverview") or "") + " " + \300                    (p.get("suiteDetails") or "")301        desc = BeautifulSoup(htmllib.unescape(desc_html),302                             "html.parser").get_text(" ", strip=True)303304        # animaux : drapeaux structurés du flux305        pets = None306        if p.get("petsNotAllowed") == 1:307            pets = "non"308        elif p.get("petFriendly") == 1:309            pets = "oui"310311        details: dict = {}312        contact: dict = {}313        if (p.get("phone") or "").strip():314            contact["phone"] = p["phone"].strip()315        email = (p.get("email") or "").split(",")[0].strip()316        if email:317            contact["email"] = email318        if contact:319            details["contact"] = contact320        try:321            if int(p.get("yearBuilt") or 0) > 1800:322                details["Année de construction"] = int(p["yearBuilt"])323            if int(p.get("floorCount") or 0) > 0:324                details["Étages"] = int(p["floorCount"])325        except (TypeError, ValueError):326            pass327328        perma = (p.get("fullPermaLink") or "").strip().strip("/")329        url = f"{BASE}/en/{perma}" if perma else BASE330331        return {"city": city, "address": address, "sector": sector,332                "lat": lat, "lng": lng, "amenities": amenities, "desc": desc,333                "pets": pets, "details": details, "url": url,334                "images": images[: self.max_images],335                "name": (p.get("buildingName") or "").strip()}336337    # -- une annonce par type d'unité disponible (rangées regroupées) ------------338    def _listing(self, bid: int, rows: list[dict], b: dict) -> Listing:339        u = rows[0]340        type_name = (u.get("typeName") or "").strip()341        unit_type = normalize_unit_type(type_name)342        bed = u.get("bedMin", u.get("bed"))343        bath = u.get("bathMin", u.get("bath"))344        if bed is not None and (not unit_type or unit_type == type_name):345            # plans nommés (« Pinnacle », « Tempo »…) : dériver des chambres346            unit_type = ("Studio" if int(bed) == 0347                         else normalize_unit_type(f"{int(bed)} chambres"))348349        # loyer : plancher du groupe (masqué sur le site si hideRateWebsites=1)350        rates: list[float] = []351        for r in rows:352            if r.get("hideRateWebsites"):353                continue354            try:355                lo = float(r.get("rateMin") or r.get("rate") or 0)356                hi = float(r.get("rateMax") or lo)357            except (TypeError, ValueError):358                continue359            if lo > 0:360                rates += [lo, max(hi, lo)]361        price = min(rates) if rates else None362        price_label = ""363        if price is not None:364            price_label = (f"À partir de {price:.0f} $" if max(rates) > price365                           else f"{price:.0f} $ /mois")366367        # superficie plausible seulement (le flux publie parfois 0)368        area = None369        for r in rows:370            try:371                v = float(r.get("sqFtMin") or r.get("sqFt") or 0)372            except (TypeError, ValueError):373                continue374            if 80 <= v <= 20000 and (area is None or v < area):375                area = v376377        # disponibilité : date structurée la plus proche du groupe378        dates = sorted(str(r.get("availabilityDate") or "").strip()[:10]379                       for r in rows380                       if _ISO_DATE_RE.match(str(r.get("availabilityDate")381                                                  or "")))382        avail_date = dates[0] if dates else None383        availability = f"Disponible le {avail_date}" if avail_date \384            else "Disponible"385        if len(rows) > 1:386            availability += f" — {len(rows)} unités"387388        details = dict(b["details"])389        if (u.get("leaseTerm") or "").strip():390            details["Bail"] = u["leaseTerm"].strip()391392        # identifiant stable : immeuble + plan (les ids d'appartements roulent)393        slug = re.sub(r"[^a-z0-9]+", "-",394                      strip_accents(type_name.lower())).strip("-")395        ext = f"{bid}-{slug or 'u'}"396        if bed is not None or bath is not None:397            ext += f"-{bed}-{bath}"398399        return Listing(400            source=self.source_id,401            external_id=ext,402            url=b["url"],403            title=f"{b['name']} — {type_name}" if type_name else b["name"],404            address=b["address"],405            sector=b["sector"],406            city=b["city"],407            province="ON",408            unit_type=unit_type,409            bedrooms=float(bed) if bed is not None else None,410            bathrooms=float(bath) if bath else None,411            price=price,412            price_label=price_label,413            availability=availability,414            availability_date=avail_date,415            area_sqft=area,416            pets=b["pets"],417            furnished=True if all(r.get("furnished") == 1418                                  for r in rows) else None,419            description=b["desc"][:600],420            amenities=b["amenities"][:25],421            details=details,422            images=b["images"],423            lat=b["lat"],424            lng=b["lng"],425        )426
Files main
Menu

Theme