SPB Git

Repository Public

killam.py 18.2 KB 430 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/killam.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/killam.py : connecteur Killam Apartment REIT (killamreit.com)91#   REIT national (~17 000 unités, Maritimes + Ontario + Alberta/C.-B.) — on ne92#   garde ici QUE l'Ontario : Toronto, Ottawa (Kanata), London, Kitchener-93#   Waterloo, Cambridge, Mississauga (~29 propriétés au moment de l'écriture).94#   Le site est un « corporate site » Yardi RentCafe derrière Cloudflare95#   (challenge JS : curl nu = 403 « Just a moment… »). Aucune API interne à96#   rejouer : la page de recherche /apartments embarque TOUT le portefeuille97#   (204 propriétés) dans un input caché `#available_prop` — un JSON doublement98#   encodé (chaîne JSON contenant du JSON aux guillemets "). On le décode99#   avec deux json.loads, sans exécuter de JavaScript : Scrapfly ASP suffit100#   (asp=true, PAS de render_js), via la chaîne de secours de BaseConnector.get101#   (Oxylabs résidentiel → Scrapfly → Bright Data).102#   Le flux liste donne nom, adresse civique, ville/province/code postal,103#   lat/lng, fourchettes loyer/chambres/sdb/pi², politique animaux, téléphone104#   et l'URL de la fiche. La fiche propriété (rendu serveur, même anti-bot)105#   fournit description, galerie photo (resource.rentcafe.com) et les cartes106#   « plans d'étage » (nom, chambres, sdb, pi², « Starting at $X /Month ») —107#   visitée via le cache BD self.detail() (clé = hash de la ligne du flux).108#   On émet UNE annonce PAR PLAN D'ÉTAGE (granularité type d'unité), avec un109#   repli « une annonce par propriété » si les cartes sont introuvables.110# -----------------------------------------------------------------------------111from __future__ import annotations112113import hashlib114import json115import os116import re117118from bs4 import BeautifulSoup119120from ..schema import Listing, normalize_unit_type121from .base import BaseConnector122123BASE = "https://www.killamreit.com"124SEARCH_PAGE = f"{BASE}/apartments"125126# Gate expansion Ontario : le connecteur reste hors registre tant que la127# variable d'environnement LOUKA_ONTARIO=1 n'est pas posée (zéro impact prod).128_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"129130# blob JSON du portefeuille dans la page de recherche (input caché)131_PROP_BLOB_RE = re.compile(132    r"id=\"available_prop\"\s+value='(.*?)'", re.S)133134# cartes plans d'étage de la fiche : « 1 Bed », « 1.5 Bath », « 415 Sq. Ft. »135_BED_RE = re.compile(r"(\d+)\s*Bed")136_BATH_RE = re.compile(r"([\d.]+)\s*Bath")137_SQFT_RE = re.compile(r"([\d,]+)\s*Sq\.?\s*Ft", re.I)138_PRICE_RE = re.compile(r"\$\s*([\d,]+)")139_FPID_RE = re.compile(r"#fp-modal-(\d+)")140# disclaimer promo servi DANS le paragraphe descriptif — retiré, pas interprété141_DISCLAIMER_RE = re.compile(142    r"Limited-time offer[^.]*\.\s*(Subject to [^.]*\.\s*)?", re.I)143_BOILERPLATE_RE = re.compile(144    r"marketing text|cookie|consent|unsubscribe|privacy policy", re.I)145146# IDs de commodités RentCafe (checkboxes du filtre corpsearch) -> libellé FR147_AMENITY_FR = {148    "1": "Air climatisé", "2": "Lave-vaisselle", "3": "Espace de rangement",149    "7": "Planchers de bois franc", "8": "Grands placards",150    "9": "Balcon/terrasse", "10": "Laveuse-sécheuse",151    "11": "Entrées laveuse-sécheuse", "12": "Accès fauteuil roulant",152    "13": "Aire BBQ/pique-nique", "14": "Centre d'affaires",153    "15": "Salle de réception", "16": "Accès contrôlé",154    "17": "Stationnement couvert", "18": "Garage",155    "19": "Internet haute vitesse", "20": "Spa", "21": "Buanderie",156    "22": "Salle multimédia", "23": "Bail court terme", "24": "Piscine",157    "25": "Salle d'entraînement", "26": "Terrain de basketball",158    "27": "Terrain de tennis", "28": "Service de garde", "29": "Aire de jeux",159    "30": "Supports à vélos", "31": "Électroménagers écoénergétiques",160    "32": "Thermostat électronique", "33": "Bâtiment écologique",161    "34": "Transport en commun à proximité", "35": "Recyclage",162}163164# villes du flux à normaliser (le flux écrit parfois « Kanata Ottawa »)165_CITY_FIX = {166    "kanata ottawa": ("Ottawa", "Kanata"),167    "kanata-ottawa": ("Ottawa", "Kanata"),168}169170171def _money(txt: str) -> float | None:172    m = _PRICE_RE.search(txt or "")173    return float(m.group(1).replace(",", "")) if m else None174175176class KillamConnector(BaseConnector):177    source_id = "killam"178    request_delay = 1.2       # Cloudflare/Scrapfly : rester très poli179    disabled = not _ONTARIO   # gate expansion Ontario (LOUKA_ONTARIO=1)180    max_properties = 40       # garde-fou (29 propriétés ON aujourd'hui)181    max_images = 20182183    # -- portefeuille : blob embarqué de la page de recherche -------------------184    def _properties(self) -> list[dict]:185        page = self.get(SEARCH_PAGE).text186        m = _PROP_BLOB_RE.search(page)187        if not m:188            raise RuntimeError("Killam : blob #available_prop introuvable "189                               "(gabarit RentCafe modifié ?)")190        # doublement encodé : value='"[{"companyid":0,…}]"'191        return json.loads(json.loads(m.group(1)))192193    def fetch(self) -> list[Listing]:194        props = self._properties()195        listings: list[Listing] = []196        count = 0197        for p in props:198            if (p.get("propertyState") or "").strip().upper() != "ON":199                continue        # REIT national : Ontario seulement ici200            if count >= self.max_properties:201                break202            count += 1203            try:204                listings.extend(self._listings(p))205            except Exception:206                continue207        return listings208209    # -- annonces d'une propriété (une par plan d'étage, repli propriété) -------210    def _listings(self, p: dict) -> list[Listing]:211        pid = str(p.get("propertyid"))212        url = ((p.get("PropertySiteUrl") or p.get("LinkUrl") or "")213               .strip().rstrip("?")) or SEARCH_PAGE214        name = (p.get("propertyName") or "").strip()215216        # adresse complète : rue + ville + « ON » + code postal217        city_raw = (p.get("propertyCity") or "").strip()218        city, sector = _CITY_FIX.get(city_raw.lower(), (city_raw, ""))219        street = (p.get("propertyAddress") or "").strip()220        postal = (p.get("propertyZipCode") or "").strip()221        full_addr = ", ".join(x for x in (street, city) if x) + ", ON"222        if postal:223            full_addr += f" {postal}"224225        # coordonnées GPS du flux (finalize() valide la bbox Ontario)226        try:227            lat = float(p.get("propertyLat")) or None228            lng = float(p.get("propertyLng")) or None229        except (TypeError, ValueError):230            lat = lng = None231232        # politique animaux : {"bNoPetsAllowed":false,"bCats":true,"bDogs":true}233        pets = None234        try:235            pol = json.loads(p.get("bPetPolicy") or "{}")236            if pol.get("bNoPetsAllowed") is True:237                pets = "non"238            elif pol.get("bCats") and pol.get("bDogs"):239                pets = "oui"240            elif pol.get("bCats") or pol.get("bDogs"):241                pets = "conditions"242        except (ValueError, TypeError):243            pass244245        # commodités : IDs RentCafe -> libellés français246        amenities = [_AMENITY_FR[a] for a in (p.get("sAmenity") or [])247                     if a in _AMENITY_FR]248249        # disponibilité : le flux n'expose qu'un booléen d'occupation + une250        # date minimale (« 1/1/0001 » = aucune affichée) — rien d'inventé251        occupied = p.get("IsFullyOccupied") is True252        availability = ("Aucune unité disponible" if occupied253                        else "Unités disponibles")254        avail_date = None255        mad = str(p.get("dtMinUnitAvailable") or "").strip()256        md = re.fullmatch(r"(\d{1,2})/(\d{1,2})/(20\d{2})", mad)257        if md:258            avail_date = f"{md.group(3)}-{int(md.group(1)):02d}-{int(md.group(2)):02d}"259260        details: dict = {}261        phone = (p.get("phone") or "").strip()262        if phone:263            details["contact"] = {"phone": phone}264265        # fiche propriété (description, galerie, plans d'étage) — via le cache266        # BD : revisitée seulement quand la ligne du flux change267        feed_key = hashlib.sha1("|".join(str(x) for x in (268            p.get("propertyMinRent"), p.get("propertyMaxRent"),269            p.get("propertyMinBed"), p.get("propertyMaxBed"),270            p.get("propertyMinArea"), p.get("propertyMaxArea"),271            p.get("IsFullyOccupied"), mad, p.get("propertyThumb"),272        )).encode("utf-8")).hexdigest()273        d = self.detail(pid, feed_key, lambda: self._fetch_detail(url))274275        desc = d.get("description") or ""276        images = list(d.get("images") or [])277        thumb = (p.get("propertyThumb") or "").strip()278        if thumb and thumb not in images:279            images.insert(0, thumb)280        images = images[: self.max_images]281282        common = dict(283            source=self.source_id, url=url, address=full_addr, sector=sector,284            city=city, province="ON", availability=availability,285            availability_date=avail_date, pets=pets, description=desc,286            amenities=amenities[:25], images=images, lat=lat, lng=lng,287        )288289        # une annonce par plan d'étage (prix/chambres/sdb/pi² précis)290        out: list[Listing] = []291        for fp in d.get("floorplans") or []:292            price = fp.get("price")293            beds = fp.get("beds")294            out.append(Listing(295                external_id=f"{pid}-{fp['fpid']}",296                title=f"{name} — {fp['name']}" if fp.get("name") else name,297                unit_type=("Studio" if beds == 0 else normalize_unit_type(298                    f"{int(beds)} chambres") if beds is not None else ""),299                bedrooms=beds,300                bathrooms=fp.get("baths"),301                price=price,302                price_label=(f"À partir de {price:.0f} $ /mois"303                             if price is not None else ""),304                area_sqft=fp.get("sqft"),305                details=dict(details),306                **common,307            ))308        if out:309            return out310311        # repli : une annonce par propriété (fourchettes du flux liste)312        price = None313        try:314            price = float(p.get("propertyMinRent") or 0) or None315        except (TypeError, ValueError):316            pass317        price_label = ""318        if price is not None:319            try:320                pmax = float(p.get("propertyMaxRent") or 0)321            except (TypeError, ValueError):322                pmax = 0.0323            price_label = (f"À partir de {price:.0f} $"324                           if pmax and pmax != price else f"{price:.0f} $ /mois")325        beds = baths = None326        try:327            bmin, bmax = float(p.get("propertyMinBed") or -1), \328                float(p.get("propertyMaxBed") or -1)329            if bmin >= 0 and bmin == bmax:330                beds = bmin331            if float(p.get("propertyMinBath") or 0) > 0:332                baths = float(p["propertyMinBath"])333        except (TypeError, ValueError):334            pass335        area = None336        try:337            v = float(p.get("propertyMinArea") or 0)338            if 80 <= v <= 20000:339                area = v340        except (TypeError, ValueError):341            pass342        return [Listing(343            external_id=pid,344            title=name,345            unit_type=("Studio" if beds == 0 else normalize_unit_type(346                f"{int(beds)} chambres") if beds is not None else ""),347            bedrooms=beds,348            bathrooms=baths,349            price=price,350            price_label=price_label,351            area_sqft=area,352            details=details,353            **common,354        )]355356    # -- fiche propriété : description + galerie + plans d'étage ----------------357    def _fetch_detail(self, url: str) -> dict:358        out: dict = {"description": "", "images": [], "floorplans": []}359        try:360            page = self.get(url).text361        except Exception:362            return out363        soup = BeautifulSoup(page, "html.parser")364365        # plans d'étage : cartes serveur « Nom / N Bed / N Bath / N Sq. Ft. /366        # Starting at $X /Month » (modal #fp-modal-<id> = identifiant stable)367        fp_imgs: set[str] = set()368        for card in soup.select(".card"):369            txt = card.get_text(" ", strip=True)370            if "Bed" not in txt and "Studio" not in txt:371                continue372            ref = card.find(attrs={"data-target": _FPID_RE})373            mid = _FPID_RE.search(ref["data-target"]) if ref else None374            if not mid:375                continue376            h = card.find(["h2", "h3", "h4"])377            mb = _BED_RE.search(txt)378            beds = (float(mb.group(1)) if mb379                    else 0.0 if "Studio" in txt else None)380            mba = _BATH_RE.search(txt)381            msq = _SQFT_RE.search(txt)382            sqft = float(msq.group(1).replace(",", "")) if msq else None383            self._append_fp(out, {384                "fpid": mid.group(1),385                "name": h.get_text(" ", strip=True) if h else "",386                "beds": beds,387                "baths": float(mba.group(1)) if mba else None,388                "sqft": sqft if sqft and 80 <= sqft <= 20000 else None,389                "price": _money(txt),390            })391            for img in card.find_all("img"):392                src = img.get("src") or img.get("data-src") or ""393                if src:394                    fp_imgs.add(src)395396        # galerie : visuels resource.rentcafe.com HORS logos et plans d'étage397        images: list[str] = []398        for img in soup.find_all("img"):399            src = (img.get("src") or img.get("data-src") or "").strip()400            if ("resource.rentcafe.com" not in src or src in fp_imgs401                    or img.find_parent(class_=re.compile(r"ysi-logo"))):402                continue403            if not img.find_parent(class_=re.compile(r"ysi-picture")):404                continue405            # variante généreuse de la transformation Cloudinary406            src = re.sub(r"c_l(?:fill|imit),w_\d+(?:,h_\d+)?",407                         "c_limit,w_1200", src)408            if src not in images:409                images.append(src)410        out["images"] = images[: self.max_images]411412        # description : paragraphes de présentation (sans le boilerplate413        # consentement/cookies ni le disclaimer promo)414        paras = []415        for ptag in soup.find_all("p"):416            t = ptag.get_text(" ", strip=True)417            if len(t) < 150 or _BOILERPLATE_RE.search(t):418                continue419            t = _DISCLAIMER_RE.sub("", t).strip()420            if t and t not in paras:421                paras.append(t)422        out["description"] = " ".join(paras)[:900]423        return out424425    @staticmethod426    def _append_fp(out: dict, fp: dict) -> None:427        """Ajoute un plan d'étage en dédoublonnant sur son identifiant."""428        if fp["fpid"] not in {f["fpid"] for f in out["floorplans"]}:429            out["floorplans"].append(fp)430
Files main
Menu

Theme