SPB Git

Repository Public

sifton.py 14.4 KB 346 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/sifton.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/sifton.py : connecteur Sifton Properties (sifton.com)91#   Gros gestionnaire/promoteur de London ON (aussi Guelph, Brantford) :92#   appartements ET maisons de ville en location longue durée (~15 communautés93#   locatives, 43 « produits » = types d'unités au moment de l'écriture).94#   Le site est un Statamic (Laravel) dont l'API de contenu REST est PUBLIQUE95#   et ouverte — aucun rendu JS ni anti-bot nécessaire (le front l'utilise96#   aussi via /api/custom/search, plus lourd car il renvoie des cartes HTML).97#   Deux requêtes suffisent :98#     - /api/collections/places/entries?limit=100 — les « places » (41, dont99#       ~15 place_type=rentals) : adresse civique complète (address_street),100#       géocodage Google embarqué (lat/lon, ville, code postal), description101#       et accordéons de commodités (landing_page.page_modules), galerie102#       photo, microsite externe éventuel (Candela, Spektra) ;103#     - /api/collections/products/entries?limit=300 — les « produits »104#       (_type_taxonomy=rental_types) : type d'unité (« 1 Bedroom »,105#       « 2 Bedroom + Den »…), sous-type apartments/townhomes, prix plancher106#       (_price, toujours « from »), pi², taxonomie beds (studio, 1-bed,107#       2_5-beds = 2 cc + den), drapeau `available`, place_slug de rattachement.108#   Une annonce PAR PRODUIT (type d'unité) rattachée à sa place — granularité109#   identique au site. Le drapeau `available` du produit pilote le texte de110#   disponibilité (les produits non disponibles restent affichés par Sifton111#   avec leur prix « Get In Touch » : on les garde, comme les plans Killam).112#   Baths : la taxonomie est « none » partout — jamais inventé (None).113#   Tout vient de l'API en 2 requêtes : pas besoin du cache BD self.detail().114#   Expansion Ontario — gaté LOUKA_ONTARIO=1 : sans la variable, disabled.115# -----------------------------------------------------------------------------116from __future__ import annotations117118import os119import re120121from bs4 import BeautifulSoup122123from ..schema import Listing, normalize_unit_type124from .base import BaseConnector125126BASE = "https://sifton.com"127PLACES_API = f"{BASE}/api/collections/places/entries"128PRODUCTS_API = f"{BASE}/api/collections/products/entries"129130# Gate expansion Ontario : hors registre tant que LOUKA_ONTARIO=1 absent131_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"132133# taxonomie beds de Statamic : « studio », « 1-bed », « 2_5-beds » (2 cc + den)134_BEDS_SLUG_RE = re.compile(r"^(\d+)(_5)?-beds?$")135136# visuels de style de vie génériques réutilisés sur plusieurs fiches — écartés137_STOCK_IMG_RE = re.compile(138    r"people-walking|balcony-lady|logo|favicon|icon", re.I)139140141def _strip_html(fragment: str) -> str:142    return BeautifulSoup(fragment or "", "html.parser").get_text(143        " ", strip=True)144145146class SiftonConnector(BaseConnector):147    source_id = "sifton"148    request_delay = 1.0149    disabled = not _ONTARIO   # gate expansion Ontario (LOUKA_ONTARIO=1)150    max_properties = 40       # garde-fou places locatives (15 au 2026-08)151    max_listings = 200        # garde-fou produits (43 au 2026-08)152    max_images = 15153154    # -- API Statamic ------------------------------------------------------------155    def _entries(self, url: str, limit: int) -> list[dict]:156        rows: list[dict] = []157        page = 1158        while page <= 10:159            data = self.get(url, params={"limit": limit, "page": page},160                            headers={"Accept": "application/json"}).json()161            rows.extend(data.get("data") or [])162            meta = data.get("meta") or {}163            if page >= int(meta.get("last_page") or 1):164                break165            page += 1166        return rows167168    # -- places locatives : contexte partagé par leurs produits -------------------169    def _rental_places(self) -> dict[str, dict]:170        out: dict[str, dict] = {}171        for p in self._entries(PLACES_API, 100):172            ptype = (p.get("place_type") or {})173            if not isinstance(ptype, dict) or ptype.get("slug") != "rentals":174                continue175            if p.get("status") not in (None, "published"):176                continue177            if len(out) >= self.max_properties:178                break179            try:180                out[p["slug"]] = self._place_ctx(p)181            except Exception:182                continue183        return out184185    def _place_ctx(self, p: dict) -> dict:186        gm = p.get("address_google_maps") or {}187        city = (gm.get("locality") or "").strip()188        street = " ".join(x for x in (189            (gm.get("streetNumber") or "").strip(),190            (gm.get("streetName") or "").strip()) if x)191        # address_street du CMS (« 550 Berkshire Drive, London, ON ») est déjà192        # complète et plus fiable que le géocodage pour les adresses multiples193        # (« 577/587/597/607 Cranbrook Road ») ; on la suffixe du code postal194        address = (p.get("address_street") or "").strip().rstrip(",")195        if not address:196            address = ", ".join(x for x in (street, city) if x) + ", ON"197        postal = (gm.get("postalCode") or "").strip()198        if postal and postal not in address:199            address += f" {postal}"200201        try:202            lat = float(gm.get("lat")) or None203            lng = float(gm.get("lon")) or None204        except (TypeError, ValueError):205            lat = lng = None206207        # description + accordéons de commodités + galerie : modules de la208        # landing page (structure Statamic, servie directement par l'API)209        desc_parts: list[str] = []210        amenities: list[str] = []211        images: list[str] = []212        card = (p.get("card_image") or {}).get("permalink")213        if card:214            images.append(card)215        modules = ((p.get("landing_page") or {}).get("page_modules")) or []216        for m in modules:217            mtype = m.get("type")218            if mtype == "two_col_text_acc":219                t = _strip_html(m.get("text_acc_content_text") or "")220                if t:221                    desc_parts.append(t)222                acc = (m.get("text_acc_content_acc") or {})223                for item in acc.get("accordion_repeater") or []:224                    for blk in item.get("acc_dropdown_content") or []:225                        soup = BeautifulSoup(blk.get("text") or "",226                                             "html.parser")227                        for li in soup.find_all("li"):228                            t = li.get_text(" ", strip=True)229                            if t and len(t) < 90 and t not in amenities:230                                amenities.append(t)231            elif mtype == "image_gallery":232                for img in m.get("images") or []:233                    u = (img.get("permalink") or "").strip()234                    if u and not _STOCK_IMG_RE.search(u) and u not in images:235                        images.append(u)236237        # URL publique : microsite externe (Candela, Spektra) sinon la fiche238        url = (p.get("external_url") or "").strip() or \239            (p.get("permalink") or "").strip() or BASE240241        return {242            "title": (p.get("title") or "").strip(),243            "address": address, "city": city, "lat": lat, "lng": lng,244            "url": url, "description": " ".join(desc_parts)[:900],245            "amenities": amenities[:25],246            "images": images[: self.max_images],247        }248249    # -- collecte : une annonce par produit locatif -------------------------------250    def fetch(self) -> list[Listing]:251        places = self._rental_places()252        listings: list[Listing] = []253        for pr in self._entries(PRODUCTS_API, 300):254            if len(listings) >= self.max_listings:255                break256            try:257                if pr.get("_type_taxonomy") != "rental_types":258                    continue259                if pr.get("status") not in (None, "published"):260                    continue261                b = places.get(pr.get("place_slug") or "")262                if b is None:263                    continue    # place non locative ou hors garde-fou264                listings.append(self._listing(pr, b))265            except Exception:266                continue267        return listings268269    def _listing(self, pr: dict, b: dict) -> Listing:270        title_raw = (pr.get("title") or "").strip()   # « 2 Bedroom + Den »271272        # chambres fermées : taxonomie beds (studio / n-bed / n_5-beds, où273        # « _5 » = den, pas une chambre) — jamais inventé274        beds = None275        slug_beds = ((pr.get("beds") or {}).get("slug") or "").strip()276        if slug_beds == "studio":277            beds = 0.0278        else:279            m = _BEDS_SLUG_RE.match(slug_beds)280            if m:281                beds = float(m.group(1))282283        # type d'unité : maison de ville -> « Maison », sinon dérivé des cc284        subtypes = pr.get("_subtypes") or []285        if "townhomes" in subtypes:286            unit_type = normalize_unit_type("townhouse")287        elif beds == 0:288            unit_type = "Studio"289        elif beds is not None:290            unit_type = normalize_unit_type(f"{int(beds)} chambres")291        else:292            unit_type = normalize_unit_type(title_raw)293294        # prix : toujours « from » chez Sifton (_price_type = from)295        price = None296        try:297            price = float(pr.get("_price") or 0) or None298        except (TypeError, ValueError):299            pass300        price_label = f"À partir de {price:.0f} $ /mois" if price else ""301302        # superficie plancher plausible (sq_ft_end = haut de fourchette)303        area = None304        try:305            v = float(pr.get("_sqft") or 0)306            if 80 <= v <= 20000:307                area = v308        except (TypeError, ValueError):309            pass310311        # baths : taxonomie « none » sur tout le catalogue -> inconnu (None)312        baths = None313        slug_baths = ((pr.get("baths") or {}).get("slug") or "").strip()314        m = re.match(r"^(\d+)(_5)?-baths?$", slug_baths)315        if m:316            baths = float(m.group(1)) + (0.5 if m.group(2) else 0.0)317318        available = pr.get("available") is True319        details: dict = {}320        if "townhomes" in subtypes:321            details["Type de bâtiment"] = "Maison de ville"322323        return Listing(324            source=self.source_id,325            external_id=(pr.get("slug") or pr.get("id") or "").strip(),326            url=b["url"],327            title=f"{b['title']} — {title_raw}" if title_raw else b["title"],328            address=b["address"],329            city=b["city"],330            province="ON",331            unit_type=unit_type,332            bedrooms=beds,333            bathrooms=baths,334            price=price,335            price_label=price_label,336            availability=("Unités disponibles" if available337                          else "Aucune unité disponible actuellement"),338            area_sqft=area,339            description=b["description"],340            amenities=b["amenities"],341            details=details,342            images=b["images"],343            lat=b["lat"],344            lng=b["lng"],345        )346
Files main
Menu

Theme