SPB Git

Repository Public

homestead.py 16.3 KB 397 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/homestead.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)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/homestead.py : connecteur Homestead Land Holdings (homestead.ca)91#   Un des 5 plus gros gestionnaires de l'Ontario (~27 000 unités, siège à92#   Kingston) : Toronto/GTA, Ottawa, Hamilton, London, Kitchener-Waterloo,93#   Kingston, Guelph, Sarnia… Le site est une SPA Rentsync « nouvelle94#   génération » (bundle cdn.rentsync.com/site/homestead_rebuild) qui parle à95#   la passerelle JSON PUBLIQUE (aucune auth, aucun anti-bot) :96#     https://website-gateway.rentsync.com/v1/homestead_rebuild/97#       properties?limit=500                        → 172 immeubles (adresse,98#           GPS, description, animaux, permaLink, cityId, modified)99#       cities/property-summary?limit=100           → cityId → nom + province100#       units?where=buildingId~in:a|b|…,status~in:enabled101#           → types d'unités avec bed/bath/pi²/prix/dispo/date (séparateur102#             multi-valeurs : « | » ; paginer via meta.totalPages)103#       properties/{id}/photos + /utilities         → galerie + services inclus104#   Photos : https://s3.amazonaws.com/lws_lift/homestead/images/gallery/full/…105#   (clé S3 « homestead », PAS « homestead_rebuild » qui sert au contenu CMS).106#   On émet UNE annonce par type d'unité DISPONIBLE (available=1), regroupées107#   par (immeuble, type, cc, sdb) — certains immeubles listent chaque logement.108#   Fiche (photos+services) via le cache BD self.detail(), clé = modified.109# -----------------------------------------------------------------------------110# Expansion Ontario — activer via LOUKA_ONTARIO=1111from __future__ import annotations112113import hashlib114import os115import re116117from bs4 import BeautifulSoup118119from ..schema import Listing, normalize_unit_type120from .base import BaseConnector121122_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"123124BASE = "https://www.homestead.ca"125GATEWAY = "https://website-gateway.rentsync.com/v1/homestead_rebuild"126# galerie S3 : tailles 512/768/1152/full — « full » validé live127IMG_BASE = "https://s3.amazonaws.com/lws_lift/homestead/images/gallery/full"128129_ISO_DATE = re.compile(r"^20\d{2}-\d{2}-\d{2}")130131132def _slug(s: str) -> str:133    return re.sub(r"[^a-z0-9]+", "-", (s or "").lower()).strip("-")134135136def _txt(html: str) -> str:137    """HTML de la passerelle → texte plat."""138    if not html:139        return ""140    return BeautifulSoup(html, "html.parser").get_text(" ", strip=True)141142143class HomesteadConnector(BaseConnector):144    source_id = "homestead"145    request_delay = 0.8146    disabled = not _ONTARIO       # Expansion Ontario — activer via LOUKA_ONTARIO=1147    max_properties = 300          # garde-fou (172 immeubles au 2026-08)148    max_images = 15149    chunk_size = 25               # immeubles par requête « units »150151    # -- passerelle JSON --------------------------------------------------------152    def _api(self, path: str, **params) -> dict:153        resp = self.get(f"{GATEWAY}/{path}", params=params,154                        headers={"Accept": "application/json",155                                 "Origin": BASE, "Referer": BASE + "/"})156        return resp.json()157158    def _api_all(self, path: str, **params) -> list[dict]:159        """Toutes les pages d'une collection (meta.totalPages)."""160        params.setdefault("limit", 500)161        out: list[dict] = []162        page = 1163        while True:164            d = self._api(path, page=page, **params)165            out.extend(d.get("data") or [])166            meta = d.get("meta") or {}167            total = meta.get("totalPages") or 1168            if page >= total:169                return out170            page += 1171172    # -- villes : cityId → (nom, code province) ---------------------------------173    def _cities(self) -> dict[int, tuple[str, str]]:174        cities: dict[int, tuple[str, str]] = {}175        try:176            for c in self._api_all("cities/property-summary", limit=100):177                cid = c.get("cityId")178                if cid is not None:179                    cities[int(cid)] = ((c.get("cityName") or "").strip(),180                                        (c.get("provinceCode") or "").strip().upper())181        except Exception:182            pass    # repli : ville dérivée du permaLink dans _listing183        return cities184185    def fetch(self) -> list[Listing]:186        cities = self._cities()187        props = self._api_all("properties")[: self.max_properties]188        by_id = {int(p["id"]): p for p in props if p.get("id") is not None}189190        # types d'unités actifs, par lots d'immeubles (séparateur « | »)191        units: list[dict] = []192        ids = list(by_id)193        for i in range(0, len(ids), self.chunk_size):194            chunk = "|".join(str(x) for x in ids[i:i + self.chunk_size])195            try:196                units.extend(self._api_all(197                    "units", where=f"buildingId~in:{chunk},status~in:enabled"))198            except Exception:199                continue200201        # regrouper les unités DISPONIBLES par (immeuble, type, cc, sdb) —202        # certains immeubles publient une ligne par logement individuel203        groups: dict[tuple, list[dict]] = {}204        for u in units:205            if not u.get("available") or u.get("hideSuiteTypeWebsite"):206                continue207            bid = int(u.get("buildingId") or 0)208            if bid not in by_id:209                continue210            key = (bid, _slug(u.get("typeName") or ""),211                   u.get("bed"), u.get("bath"))212            groups.setdefault(key, []).append(u)213214        listings: list[Listing] = []215        for key, grp in groups.items():216            try:217                listings.append(self._listing(by_id[key[0]], grp, cities))218            except Exception:219                continue220        return listings221222    # -- une annonce par type d'unité disponible dans un immeuble ---------------223    def _listing(self, p: dict, grp: list[dict],224                 cities: dict[int, tuple[str, str]]) -> Listing:225        pid = int(p["id"])226        u0 = grp[0]227        type_name = (u0.get("typeName") or "").strip()228        name = (p.get("buildingName") or "").strip()229        perma = (p.get("permaLink") or "").strip()230        url = f"{BASE}/residential/{perma}" if perma else BASE231232        # ville : mapping cityId → nom officiel ; repli = dernier segment du slug233        city, prov = cities.get(int(p.get("cityId") or 0), ("", "ON"))234        if not city and perma:235            city = perma.rsplit("-", 1)[-1].replace("-", " ").title()236237        # adresse complète : rue + ville + ON + code postal238        street = " ".join(x for x in ((p.get("streetNumber") or "").strip(),239                                      (p.get("streetName") or "").strip()) if x)240        postal = (p.get("postal") or "").strip()241        full_addr = ", ".join(x for x in (street, city) if x)242        if full_addr:243            full_addr += f", ON {postal}".rstrip()244245        # coordonnées GPS structurées de la passerelle246        try:247            lat = float(p["latitude"]) if p.get("latitude") else None248            lng = float(p["longitude"]) if p.get("longitude") else None249        except (TypeError, ValueError):250            lat = lng = None251252        # prix : plus bas tarif affichable du groupe (0 = prix masqué)253        rates = []254        for u in grp:255            if u.get("hideRateWebsites"):256                continue257            try:258                r = float(u.get("rate") or 0)259            except (TypeError, ValueError):260                r = 0.0261            if r > 0:262                rates.append(r)263        price = min(rates) if rates else None264        price_label = ""265        if price is not None:266            price_label = (f"À partir de {price:.0f} $"267                           if len(grp) > 1 or (rates and max(rates) != price)268                           else f"{price:.0f} $ /mois")269270        # disponibilité : plus proche date du groupe (None = maintenant)271        dates = sorted(str(u.get("availabilityDate") or "")[:10]272                       for u in grp if _ISO_DATE.match(273                           str(u.get("availabilityDate") or "")))274        avail_date = dates[0] if dates else None275        availability = (f"Disponible le {avail_date}" if avail_date276                        else "Disponible maintenant")277278        # superficie : plus petite valeur plausible du groupe279        area = None280        for u in grp:281            for k in ("sqFt", "sqFtMin"):282                try:283                    v = float(u.get(k) or 0)284                except (TypeError, ValueError):285                    continue286                if 80 <= v <= 20000 and (area is None or v < area):287                    area = v288289        # chambres / salles de bain : champs structurés de l'unité290        try:291            bedrooms = float(u0["bed"]) if u0.get("bed") is not None else None292            bathrooms = float(u0["bath"]) if u0.get("bath") is not None else None293        except (TypeError, ValueError):294            bedrooms = bathrooms = None295        unit_type = ("Studio" if bedrooms == 0296                     else normalize_unit_type(type_name))297298        # animaux : indicateurs structurés de l'immeuble299        if p.get("petsNotAllowed"):300            pets = "non"301        elif p.get("petFriendly"):302            pets = "oui"303        else:304            pets = None305306        # description : aperçu de l'immeuble + détails de suites (HTML → texte)307        desc = " ".join(x for x in (308            _txt(p.get("buildingOverview") or ""),309            _txt(p.get("suiteDetails") or ""),310        ) if x)[:800]311312        # commodités : caractéristiques de l'immeuble + services inclus (fiche)313        amenities: list[str] = []314        for t in re.split(r"[\n;•]|</li>|<li>",315                          p.get("buildingFeatures") or ""):316            t = _txt(t)317            if t and t not in amenities:318                amenities.append(t)319320        # champs structurés321        details: dict = {}322        contact: dict = {}323        if (p.get("phone") or "").strip():324            contact["phone"] = p["phone"].strip()325        if (p.get("email") or "").strip():326            contact["email"] = p["email"].strip()327        if contact:328            details["contact"] = contact329        if (p.get("neighbourhood") or "").strip():330            details["Quartier"] = p["neighbourhood"].strip()331332        # fiche (galerie photo + services inclus) via le cache BD : revisitée333        # seulement quand l'immeuble change (horodatage « modified »)334        det_key = hashlib.sha1(str(p.get("modified") or "").encode()).hexdigest()335        d = self.detail(f"b{pid}", det_key, lambda: self._fetch_detail(pid))336        for t in d.get("utilities") or []:337            t = f"{t} incluse" if t in ("Eau", "Électricité") else t338            if t and t not in amenities:339                amenities.append(t)340        images = list(d.get("images") or [])341342        return Listing(343            source=self.source_id,344            external_id=f"{pid}-{_slug(type_name) or 'unite'}-"345                        f"{u0.get('bed')}cc-{u0.get('bath')}sdb",346            url=url,347            title=f"{name} — {type_name}" if type_name else name,348            address=full_addr,349            sector=(p.get("neighbourhood") or "").strip(),350            city=city,351            province=prov or "ON",352            unit_type=unit_type,353            bedrooms=bedrooms,354            bathrooms=bathrooms,355            price=price,356            price_label=price_label,357            availability=availability,358            availability_date=avail_date,359            area_sqft=area,360            pets=pets,361            description=desc,362            amenities=amenities[:25],363            details=details,364            images=images[: self.max_images],365            lat=lat,366            lng=lng,367        )368369    # -- fiche immeuble : galerie photo + services inclus (2 appels, cachés) ----370    def _fetch_detail(self, pid: int) -> dict:371        out: dict = {"images": [], "utilities": []}372        # traductions FR des services inclus les plus fréquents373        fr = {"Water": "Eau", "Heat": "Chauffage", "Hydro": "Électricité",374              "Electricity": "Électricité", "Internet": "Internet",375              "Cable": "Câble"}376        try:377            photos = self._api_all(f"properties/{pid}/photos", limit=100)378        except Exception:379            photos = []380        photos = [ph for ph in photos381                  if ph.get("active") and (ph.get("image") or "").strip()]382        photos.sort(key=lambda ph: (0 if ph.get("mainGallery") else 1,383                                    ph.get("orderBy") or 0))384        for ph in photos:385            u = f"{IMG_BASE}/{ph['image'].strip()}"386            if u not in out["images"]:387                out["images"].append(u)388        out["images"] = out["images"][: self.max_images]389        try:390            for ut in self._api_all(f"properties/{pid}/utilities", limit=50):391                t = (ut.get("name") or "").strip()392                if t:393                    out["utilities"].append(fr.get(t, t))394        except Exception:395            pass396        return out397
Files main
Menu

Theme