SPB Git

Repository Public

summit.py 14.7 KB 362 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/summit.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/summit.py : connecteur Summit Property Management91#   (summitmanagement.ca — 3 000+ unités à Montréal : Vue/Triangle, LIV,92#   Allegra, IVY, Le V, Le Duke, Skyla, Le 400 Sherbrooke Ouest, RIVA…).93#   Plateforme Rentsync/LiftSystem : la page /apartments expose client_id et94#   city_ids (div.search-data) et son /scripts/main.js embarque le jeton95#   public du flux officiel https://api.theliftsystem.com/v2/search — aucun96#   rendu JavaScript nécessaire. Comme hazelview.py, on interroge le flux par97#   nombre de chambres (min_bed/max_bed + only_available_suites) pour obtenir,98#   par immeuble ET par type d'unité, les loyers réels (stats min/max), la99#   superficie et le nombre d'unités disponibles -> une annonce par immeuble100#   et par type d'unité (uid stables « <id>-<n>bed »).101#   ⚠️ Gestionnaire pancanadien (Ottawa aussi servie par le même flux) :102#   garde-fou province_code == QC — seules les propriétés montréalaises103#   passent. La fiche immeuble du site (rendu serveur) fournit la galerie104#   assets.rentsync.com, via le cache BD self.detail() (revisitée seulement105#   quand la ligne du flux change).106# -----------------------------------------------------------------------------107from __future__ import annotations108109import hashlib110import re111112from bs4 import BeautifulSoup113114from ..schema import Listing, strip_accents115from .base import BaseConnector116117BASE = "https://www.summitmanagement.ca"118SEARCH_PAGE = f"{BASE}/apartments"119LIFT_API = "https://api.theliftsystem.com/v2/search"120121# Valeurs observées sur la page/main.js — repli si l'extraction dynamique casse122DEFAULT_CLIENT_ID = "162"123DEFAULT_AUTH_TOKEN = "sswpREkUtyeYjeoahA2i"    # jeton public (main.js, prod)124MONTREAL_CITY_ID = "1863"                      # Montréal dans la base Lift125126SEARCH_PARAMS = ("only_available_suites=true&show_all_properties=false"127                 "&min_bath=-1&max_bath=10&min_rate=0&max_rate=20000")128129# jeton de la branche production de main.js :130# a="https://api.theliftsystem.com/v2/search?locale="+s+"&",o="&auth_token=…"131_TOKEN_RE = re.compile(132    r'api\.theliftsystem\.com/v2/search\?locale="\+\w+\+"&",'133    r'\w+="&auth_token=([A-Za-z0-9]+)"')134_MAINJS_RE = re.compile(r'src="(/scripts/main\.js[^"]*)"')135# galerie de la fiche immeuble (assets Rentsync, rendu serveur)136_IMG_RE = re.compile(137    r"https://assets\.rentsync\.com/[^\"'\\)\s]+\.(?:jpg|jpeg|png|webp)", re.I)138_SKIP_IMG = re.compile(r"logo|icon|favicon|badge|theme-settings|/256/", re.I)139_TAG_RE = re.compile(r"<[^>]+>")140141# (min_bed, max_bed, type d'unité Lou-Ka)142_BED_QUERIES = [(0, 0, "Studio"), (1, 1, "3½"), (2, 2, "4½"),143                (3, 3, "5½"), (4, 5, "6½+")]144145# Villes QC admissibles (l'API renvoie aussi Ottawa pour ce client)146_QC_CITIES = {"montreal": "Montréal"}147148149class SummitConnector(BaseConnector):150    source_id = "summit"151    request_delay = 0.7152    max_details = 30         # garde-fou pages immeuble (vraies requêtes/sync)153    max_images = 20154155    # -- paramètres du flux (page + main.js, avec replis) ----------------------156    def _feed_params(self) -> tuple[str, str, str]:157        """(client_id, city_ids, auth_token) lus sur le site, replis constants."""158        client_id, city_ids, token = (DEFAULT_CLIENT_ID, MONTREAL_CITY_ID,159                                      DEFAULT_AUTH_TOKEN)160        try:161            page = self.get(SEARCH_PAGE).text162            soup = BeautifulSoup(page, "html.parser")163            data = soup.find("div", class_="search-data")164            if data:165                client_id = (data.get("data-client-id") or client_id).strip()166                ids = (data.get("data-city-ids-string") or "").strip()167                if ids:            # le filtre province élimine Ottawa ensuite168                    city_ids = ids169            m = _MAINJS_RE.search(page)170            if m:171                js = self.get(BASE + m.group(1)).text172                mt = _TOKEN_RE.search(js)173                if mt:174                    token = mt.group(1)175        except Exception:176            pass    # replis : les constantes observées177        return client_id, city_ids, token178179    def fetch(self) -> list[Listing]:180        client_id, city_ids, token = self._feed_params()181182        listings: list[Listing] = []183        seen: set[str] = set()184        for min_bed, max_bed, unit_type in _BED_QUERIES:185            try:186                props = self._search(client_id, token, city_ids,187                                     min_bed, max_bed)188            except Exception:189                continue190            if not isinstance(props, list):191                continue192            for p in props:193                try:194                    lst = self._prop_listing(p, unit_type, min_bed)195                    if lst and lst.external_id not in seen:196                        seen.add(lst.external_id)197                        listings.append(lst)198                except Exception:199                    continue200201        # galerie de la fiche immeuble (cache BD, 1 requête par immeuble)202        self._fetched = 0203        memo: dict[str, dict] = {}204        for lst in listings:205            pid = lst.external_id.split("-")[0]206            if not lst.url:207                continue208            if pid not in memo:209                key = hashlib.sha1(210                    f"{lst.availability}|{lst.price}|{lst.images[:1]}"211                    .encode("utf-8")).hexdigest()212                try:213                    memo[pid] = self.detail(214                        pid, key, lambda u=lst.url: self._fetch_gallery(u))215                except Exception:216                    memo[pid] = {}217            extra = [u for u in (memo[pid].get("images") or [])218                     if u not in lst.images]219            lst.images = (lst.images + extra)[: self.max_images]220        return listings221222    def _search(self, client_id: str, token: str, city_ids: str,223                min_bed: int, max_bed: int) -> list:224        url = (f"{LIFT_API}?locale=en&client_id={client_id}"225               f"&auth_token={token}&city_ids={city_ids}"226               f"&min_bed={min_bed}&max_bed={max_bed}"227               f"&{SEARCH_PARAMS}&limit=100")228        return self.get(url, headers={"Accept": "application/json",229                                      "Referer": BASE + "/"}).json()230231    # -- une annonce par immeuble et par type d'unité ---------------------------232    def _prop_listing(self, p: dict, unit_type: str,233                      beds: int) -> Listing | None:234        if not p.get("availability_count"):235            return None236        addr = p.get("address") or {}237        if (addr.get("province_code") or "").upper() != "QC":238            return None         # gestionnaire pancanadien : Ottawa exclue239        city = _QC_CITIES.get(240            strip_accents((addr.get("city") or "").strip().lower()))241        if not city:242            return None         # ville QC inattendue : ne rien inventer243244        stats = ((p.get("statistics") or {}).get("suites") or {})245        rates = stats.get("rates") or {}246        sq = stats.get("square_feet") or {}247248        def _num(v):249            try:250                v = float(v)251            except (TypeError, ValueError):252                return None253            return v254255        rmin, rmax = _num(rates.get("min")), _num(rates.get("max"))256        # le flux publie parfois des sentinelles (0.01 $) — prix plausibles only257        price = rmin if rmin and 300 <= rmin <= 20000 else None258        if price and rmax and rmax != rmin:259            price_label = f"À partir de {int(price)} $ (max {int(rmax)} $)"260        elif price:261            price_label = f"{int(price)} $/mois"262        else:263            price_label = ""264265        sqmin = _num(sq.get("min"))266        area = sqmin if sqmin and 80 <= sqmin <= 20000 else None267268        details_src = p.get("details") or {}269        desc = _TAG_RE.sub(" ", details_src.get("overview") or "")270        desc = re.sub(r"\s+", " ", desc).strip()[:500]271        sbits = [f"{p['availability_count']} unité(s) disponible(s)"]272273        amenities: list[str] = []274        for a in p.get("amenities") or []:275            t = (a.get("name") if isinstance(a, dict) else str(a) or "").strip()276            if t and t not in amenities:277                amenities.append(t)278279        pid = p.get("id")280        name = (p.get("name") or "").strip()281        geo = p.get("geocode") or {}282        try:283            lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))284        except (TypeError, ValueError):285            lat = lng = None286287        pets = None288        if isinstance(p.get("pet_friendly"), bool):289            pets = "oui" if p["pet_friendly"] else None   # false ≠ « interdit »290291        details: dict = {"building": name} if name else {}292        contact = p.get("contact") or {}293        cinfo: dict = {}294        if (contact.get("phone") or "").strip():295            cinfo["phone"] = contact["phone"].strip()296        for em in (contact.get("email") or "").split(","):297            em = em.strip()298            if em and "leadmanaging" not in em:299                cinfo["email"] = em300                break301        if cinfo:302            details["contact"] = cinfo303304        images = []305        if p.get("photo_path"):306            images.append(p["photo_path"])307308        # le site marque certains immeubles « furnished » dans le permalink309        furnished = True if "/furnished/" in (p.get("permalink") or "") else None310311        return Listing(312            source=self.source_id,313            external_id=f"{pid}-{beds}bed",314            url=(p.get("permalink") or SEARCH_PAGE).strip(),315            title=f"{name} — {unit_type}",316            address=", ".join(x for x in [317                (addr.get("address") or "").strip(), city,318                (addr.get("postal_code") or "").strip()] if x),319            sector=(addr.get("neighbourhood") or "").strip(),320            city=city,321            unit_type=unit_type,322            price=price,323            price_label=price_label,324            availability=(p.get("min_availability_date")325                          or p.get("availability_status_label") or ""),326            area_sqft=area,327            pets=pets,328            furnished=furnished,329            description=" — ".join([desc] + sbits if desc else sbits)[:600],330            amenities=amenities[:25],331            details=details,332            images=images,333            lat=lat,334            lng=lng,335        )336337    # -- galerie de la fiche immeuble (rendu serveur) ---------------------------338    def _fetch_gallery(self, url: str) -> dict:339        """Photos assets.rentsync.com de la fiche (variante /1152/ préférée)."""340        if self._fetched >= self.max_details:341            raise RuntimeError("budget de pages immeuble atteint")342        self._fetched += 1343        out: dict = {"images": []}344        try:345            page = self.get(url).text346        except Exception:347            return out348        urls = _IMG_RE.findall(page)349        images: list[str] = []350        seen: set[str] = set()351        for u in urls:352            if _SKIP_IMG.search(u):353                continue354            fname = u.rsplit("/", 1)[-1]355            if fname in seen:356                continue357            big = u.replace("/512/", "/1152/")358            seen.add(fname)359            images.append(big if big in urls else u)360        out["images"] = images[: self.max_images]361        return out362
Files main
Menu

Theme