SPB Git

Repository Public

rentcafe.py 24.5 KB 568 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/rentcafe.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/rentcafe.py : connecteur GÉNÉRIQUE Yardi RentCafe/SecureCafe91#   (multi-clients Ontario — levier n° 2 de l'expansion, voir92#    gestion-immobiliere-ontario.md §10)93#94#   Une sous-classe est générée dynamiquement par client du registre95#   data/rentcafe_clients.json (statut « ok ») : source_id = rc_<id>96#   (vague 1 2026-08-26 : rc_effort, rc_osgoode, rc_gwlra, rc_oshanter ;97#    vague 2 2026-08-27 : rc_claridge, rc_richcraft, rc_arnon, rc_concert,98#    rc_caraco). Le registre auto-découvrant connectors/__init__.py les99#   ramasse dans vars(module).100#101#   Pattern « searchlisting » (validé sur les 9 clients actifs) :102#   1) <site>/searchlisting.aspx via Scrapfly (Cloudflare 403 en direct,103#      contenu rendu côté serveur -> render_js inutile) :104#      - cartes li.property-box-hidden : nom, lien fiche, adresse complète105#        (« …, Kingston, ON K7P 1M8 »), lits/sdb/pi², fourchette de prix,106#        téléphone, vignette resource.rentcafe.com ;107#      - champ caché available_prop_map (JSON doublement encodé) :108#        propertyid -> lat/lng + fourchette de prix des épingles de carte.109#      Seules les cartes dont l'adresse est en Ontario sont conservées110#      (Osgoode/GWLRA listent aussi AB/BC ; le QC reste aux connecteurs QC).111#   2) fiche propriété (+ /floorplans au besoin) via self.detail() (cache BD,112#      budget Scrapfly par synchronisation) : galerie, description, plans113#      structurés fp-container (2 gabarits : spans data-selenium-id ou cartes114#      h2.card-title + nu-bed/nu-bathroom/nu-area + data-floorplan-*).115#   Une annonce par propriété (uid stable = propertyid RentCafe) ; comme chez116#   Osgoode, AUCUN décompte d'unités disponibles n'est publié -> availability117#   reste vide (rien d'inventé).118#119#   Pattern « securecafe » (<client>.securecafe.com/residentservices/120#   apartmentsforrent/…) : vérifié fermé derrière login chez Old Oak,121#   Paramount et Tricar — entrées « echec » du registre, aucune classe122#   générée (voir les notes du registre avant de réessayer). Les autres123#   impasses vérifiées (WordPress sans searchlisting, microsites par124#   immeuble, Entrata, Rentsync, sites custom) sont aussi documentées125#   en « echec » dans le registre.126#127#   ⚠ Gate Ontario : les classes ne sont actives que si LOUKA_ONTARIO=1 —128#   sans cette variable, disabled=True et le registre des connecteurs les129#   ignore (zéro impact sur la prod Québec).130# -----------------------------------------------------------------------------131from __future__ import annotations132133import hashlib134import html as htmllib135import json136import os137import re138139from bs4 import BeautifulSoup140141from ..schema import Listing, parse_price142from .base import BaseConnector143144# Gate expansion Ontario (voir en-tête)145_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"146147_REGISTRY_PATH = os.path.join(os.path.dirname(__file__), "..", "..",148                              "data", "rentcafe_clients.json")149150# « $1,449.00 - $1,899.00 » / « $1,499.00 » (format RentCafe, virgule = milliers)151_PRICE_RE = re.compile(r"\$[\d,]+(?:\.\d{2})?(?:\s*(?:-|to|à)+\s*"152                       r"\$[\d,]+(?:\.\d{2})?)?")153_NUM_RE = re.compile(r"[\d,]+(?:\.\d+)?")154_SKIP_IMG = re.compile(r"logo|icon|favicon|placeholder|\.svg", re.I)155_PHONE_RE = re.compile(r"\(?([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-]?(\d{4})")156157# nombre de chambres -> type d'unité (normalize_unit_type fera la conversion158# canonique n½ à l'ingestion ; on passe le texte source, rien d'inventé)159_BED_TYPES = {0: "Studio", 1: "1 Bed", 2: "2 Beds", 3: "3 Beds", 4: "4 Beds"}160161162def _to_float(txt: str) -> float | None:163    m = _NUM_RE.search(txt or "")164    if not m:165        return None166    try:167        return float(m.group(0).replace(",", ""))168    except ValueError:169        return None170171172def _low_price(txt: str) -> float | None:173    """Borne basse d'une fourchette « $1,449.00 - $1,899.00 » (100-20000 $)."""174    vals = [_to_float(v) for v in re.findall(r"\$[\d,]+(?:\.\d{2})?", txt or "")]175    vals = [v for v in vals if v is not None and 100 <= v <= 20000]176    return min(vals) if vals else None177178179class _DetailBudget(Exception):180    """Budget de nouvelles fiches Scrapfly épuisé pour cette synchronisation."""181182183class RentCafeClientConnector(BaseConnector):184    """Classe de base des clients RentCafe — ne PAS l'enregistrer telle quelle185    (source_id vide) : les sous-classes concrètes sont générées plus bas à186    partir du registre data/rentcafe_clients.json."""187188    source_id = ""                 # vide -> ignorée par connectors/__init__.py189    disabled = not _ONTARIO        # gate expansion Ontario190    request_delay = 1.5            # Scrapfly coûte : politesse renforcée191    client: dict = {}              # entrée du registre (site, search_url…)192    max_properties = 160           # garde-fou (Effort Trust : 153 cartes ON)193    max_details = 8                # nouvelles fiches Scrapfly max par sync194    max_images = 20195196    # -- Scrapfly (Cloudflare -> ASP ; contenu rendu serveur, pas de JS) -------197    def _page(self, url: str) -> str:198        res = self.scrapfly(url, render_js=False, asp=True, country="ca")199        if (res.get("status_code") or 0) != 200:200            return ""201        return res.get("content") or ""202203    # -- fetch ------------------------------------------------------------------204    def fetch(self) -> list[Listing]:205        if (self.client.get("pattern") or "searchlisting") != "searchlisting":206            return []              # « securecafe » public : aucun client validé207        html = self._page(self.client["search_url"])208        if not html:209            raise RuntimeError(210                f"searchlisting inaccessible via Scrapfly ({self.source_id})")211        soup = BeautifulSoup(html, "html.parser")212        pins = self._map_pins(html)213214        self._detail_fetches = 0215        listings: list[Listing] = []216        seen: set[str] = set()217        cards = soup.select("li.property-box-hidden") \218            or soup.select("li.property-box, .property-box")219        for card in cards:220            if len(listings) >= self.max_properties:221                break222            try:223                lst = self._property_listing(card, pins)224                if lst and lst.external_id not in seen:225                    seen.add(lst.external_id)226                    listings.append(lst)227            except Exception:228                continue229        return listings230231    # -- épingles de carte (champ caché available_prop_map) ----------------------232    @staticmethod233    def _map_pins(html: str) -> dict[str, dict]:234        """propertyid -> {lat, lng, price, beds} (JSON doublement encodé)."""235        m = re.search(r"available_prop_map[^>]*value=(['\"])(.*?)\1", html, re.S)236        if not m:237            return {}238        try:239            data = json.loads(htmllib.unescape(m.group(2)))240            if isinstance(data, str):241                data = json.loads(data)242            pins = data.get("ListingsPins")243            if isinstance(pins, str):244                pins = json.loads(pins)245        except (ValueError, AttributeError):246            return {}247        out: dict[str, dict] = {}248        for grp in (pins or {}).get("groups") or []:249            for p in grp.get("points") or []:250                pid = str(p.get("propertyid") or p.get("id") or "")251                if not pid:252                    continue253                hover = p.get("hover") or {}254                out[pid] = {"lat": p.get("y"), "lng": p.get("x"),255                            "price": hover.get("Price") or "",256                            "beds": hover.get("Beds") or ""}257        return out258259    # -- carte propriété ----------------------------------------------------------260    def _property_listing(self, card, pins: dict[str, dict]) -> Listing | None:261        a = card.select_one(".property-name a") or card.select_one("h3 a")262        if not a or not a.get("href"):263            return None264        url = (a.get("href") or "").strip()265        if url.startswith("/"):266            url = self.client["site"].rstrip("/") + url267        url = url.split("?")[0].rstrip("/")268269        name = re.sub(r"\s*opens in a new tab\s*", "",270                      a.get_text(" ", strip=True)).strip()271272        addr_el = card.select_one(".card-prop-address")273        address = addr_el.get_text(" ", strip=True) if addr_el else ""274        # Ontario seulement (Osgoode/GWLRA listent aussi AB/BC ; QC = connecteurs QC)275        if not re.search(r",\s*ON(?:\s|,|$)", address):276            return None277        city = ""278        parts = [p.strip() for p in address.split(",")]279        for i, p in enumerate(parts):280            if re.match(r"^ON(\s|$)", p) and i > 0:281                city = parts[i - 1]282                break283284        # propertyid RentCafe stable (classe track-propertyurl-<id> ou épingle)285        pid = ""286        for el in card.select("[class*='track-propertyurl-']"):287            for cl in el.get("class") or []:288                if cl.startswith("track-propertyurl-"):289                    pid = cl.rsplit("-", 1)[-1]290                    break291        slug = re.sub(r"[^a-z0-9]+", "-",292                      url.rstrip("/").rsplit("/", 1)[-1].lower()).strip("-")293        external_id = pid or slug294        if not external_id:295            return None296297        # lits / sdb / pi² de la carte (« 1.0Beds - 2.0Beds », « 799 - 1,018 Sq. Ft. »)298        beds_txt = baths_txt = sqft_txt = ""299        meta = card.select_one(".card-bed-bath-rent")300        if meta:301            for li in meta.select("li"):302                it = li.get_text(" ", strip=True)303                if "Bed" in it:304                    beds_txt = it305                elif "Bath" in it:306                    baths_txt = it307                elif "Sq" in it:308                    sqft_txt = re.sub(r"\s*to\s*-\s*", " - ", it)309        unit_type = ""310        bm = re.match(r"^(\d+)(?:\.\d+)?\s*Beds?", beds_txt or "")311        if bm and "-" not in beds_txt.split("Bed")[0]:312            unit_type = _BED_TYPES.get(int(bm.group(1)), "")313314        # fourchette de prix : carte, sinon épingle de la carte interactive315        pin = pins.get(external_id) or {}316        pm = _PRICE_RE.search(card.get_text(" ", strip=True))317        price_label = pm.group(0) if pm else (pin.get("price") or "")318        price_label = re.sub(r"\s*(?:to|à)\s*", " - ", price_label).strip()319        price = _low_price(price_label)320        if price is not None and "-" in price_label:321            price_label = "À partir de " + price_label322        if price is None:323            price_label = ""       # « Call for Details » : rien d'inventé324325        phone = ""326        tel = card.select_one("a[href^='tel:']")327        if tel:328            tm = _PHONE_RE.search(tel.get("href") or "")329            if tm:330                phone = f"{tm.group(1)}-{tm.group(2)}-{tm.group(3)}"331332        images: list[str] = []333        img = card.select_one("img[src*='rentcafe']") or card.select_one("img")334        if img and (img.get("src") or "").startswith("http") \335                and not _SKIP_IMG.search(img.get("src") or ""):336            images.append(img["src"])337338        # fiche + plans via cache BD (clé = contenu de la carte liste)339        key = hashlib.sha1(340            f"{name}|{address}|{beds_txt}|{baths_txt}|{sqft_txt}|{price_label}"341            .encode("utf-8")).hexdigest()342        try:343            payload = self.detail(external_id, key,344                                  lambda: self._fetch_detail(url))345        except _DetailBudget:346            payload = {}347        except Exception:348            payload = {}349350        for im in payload.get("images") or []:351            if im not in images:352                images.append(im)353354        # plans structurés : prix « à partir de » réel + résumé fidèle355        plans = payload.get("floorplans") or []356        prices = [p["price"] for p in plans357                  if p.get("price") and 100 <= p["price"] <= 20000]358        if prices:359            price = min(prices)360            price_label = (f"À partir de {price:,.0f} $/mois".replace(",", " ")361                           if len(plans) > 1 or "-" in price_label362                           else f"{price:,.0f} $/mois".replace(",", " "))363        sqfts = [p["sqft"] for p in plans if p.get("sqft")]364        area_sqft = min(sqfts) if sqfts else None365        if len(plans) == 1 and plans[0].get("unit_type"):366            unit_type = plans[0]["unit_type"]367        plan_bits = []368        for p in plans[:8]:369            seg = p.get("name") or ""370            if p.get("sqft"):371                seg += f" ({p['sqft']:.0f} pi²)"372            if p.get("price"):373                seg += f" : {p['price']:,.0f} $/mois".replace(",", " ")374            if seg:375                plan_bits.append(seg)376377        bathrooms = None378        tb = re.match(r"^(\d+(?:\.\d+)?)\s*Bath", baths_txt or "")379        if tb and "-" not in baths_txt.split("Bath")[0]:380            bathrooms = float(tb.group(1))381382        details: dict = {}383        if phone:384            details["contact"] = {"phone": phone}385386        desc_parts = ([payload["description"]]387                      if payload.get("description") else [])388        desc_parts += [b for b in [beds_txt, baths_txt, sqft_txt] if b]389        if plan_bits:390            desc_parts.append("Plans : " + " ; ".join(plan_bits))391392        lat = pin.get("lat")393        lng = pin.get("lng")394395        return Listing(396            source=self.source_id,397            external_id=str(external_id),398            url=url,399            title=name or slug.replace("-", " ").title(),400            address=address,401            sector="",           # le gabarit RentCafe ne publie pas le quartier402            city=city,403            province="ON",404            unit_type=unit_type,405            bathrooms=bathrooms,406            price=price,407            price_label=price_label,408            availability="",     # aucun décompte d'unités publié (cf. en-tête)409            area_sqft=area_sqft,410            description=" — ".join(desc_parts)[:900],411            details=details,412            images=images[: self.max_images],413            lat=float(lat) if isinstance(lat, (int, float)) else None,414            lng=float(lng) if isinstance(lng, (int, float)) else None,415        )416417    # -- fiche propriété (galerie + description + plans) --------------------------418    def _fetch_detail(self, url: str) -> dict:419        if self._detail_fetches >= self.max_details:420            raise _DetailBudget()421        self._detail_fetches += 1422423        payload: dict = {"description": "", "images": [], "floorplans": []}424        html = self._page(url)425        if html:426            soup = BeautifulSoup(html, "html.parser")427            for im in soup.select("img[src*='resource.rentcafe.com']"):428                src = im.get("src") or ""429                if src and not _SKIP_IMG.search(src) \430                        and src not in payload["images"]:431                    payload["images"].append(src)432            paras = [p.get_text(" ", strip=True) for p in soup.find_all("p")]433            paras = [p for p in paras if len(p) > 80]434            if paras:435                payload["description"] = " ".join(paras[:2])[:600]436            payload["floorplans"] = self._parse_floorplans(soup)437438        # plans absents de la fiche (gabarit Osgoode/GWLRA) -> page /floorplans439        if not payload["floorplans"] and not url.endswith("default.aspx") \440                and self._detail_fetches < self.max_details:441            self._detail_fetches += 1442            fp_html = self._page(url + "/floorplans")443            if fp_html:444                payload["floorplans"] = self._parse_floorplans(445                    BeautifulSoup(fp_html, "html.parser"))446        return payload447448    # -- plans fp-container (2 gabarits RentCafe) ----------------------------------449    @staticmethod450    def _parse_floorplans(soup) -> list[dict]:451        """Cartes de plans : nom, chambres, sdb, pi², prix (borne basse d'une452        fourchette). Gabarits : spans data-selenium-id (Osgoode) OU cartes453        h2.card-title + icônes nu-bed/nu-bathroom/nu-area + attributs454        data-floorplan-* (Effort, GWLRA). Dédoublonnés par id (carrousels)."""455        plans: list[dict] = []456        seen: set[str] = set()457        for cont in soup.select("div[id^='fp-container-']"):458            fpid = (cont.get("id") or "").rsplit("-", 1)[-1]459            if fpid in seen:460                continue461            seen.add(fpid)462            try:463                plan: dict = {}464                # gabarit 1 : spans data-selenium-id465                name_el = cont.select_one("span[data-selenium-id$='Name']")466                # gabarit 2 : cartes (titre + icônes)467                if name_el is None:468                    name_el = cont.select_one("h2.card-title, .card-title")469                if name_el is not None:470                    plan["name"] = name_el.get_text(" ", strip=True)471472                beds_el = cont.select_one("span[data-selenium-id$='Beds']")473                beds_txt = (beds_el.get_text(" ", strip=True) if beds_el474                            else "")475                if not beds_txt:476                    ic = cont.select_one(".nu-bed")477                    if ic and ic.parent:478                        beds_txt = ic.parent.get_text(" ", strip=True)479                bm = re.search(r"(\d+)\s*Bed", beds_txt)480                if bm:481                    plan["bedrooms"] = float(bm.group(1))482                    plan["unit_type"] = _BED_TYPES.get(int(bm.group(1)), "")483                elif re.search(r"studio", (plan.get("name") or "") + beds_txt,484                               re.I):485                    plan["bedrooms"] = 0.0486                    plan["unit_type"] = "Studio"487488                baths_el = cont.select_one("span[data-selenium-id$='Baths']")489                baths_txt = (baths_el.get_text(" ", strip=True) if baths_el490                             else "")491                if not baths_txt:492                    ic = cont.select_one(".nu-bathroom")493                    if ic and ic.parent:494                        baths_txt = ic.parent.get_text(" ", strip=True)495                tm = re.search(r"(\d+(?:\.\d+)?)\s*Bath", baths_txt)496                if tm:497                    plan["bathrooms"] = float(tm.group(1))498499                sq_el = cont.select_one("span[data-selenium-id$='SqFt']")500                sq_txt = sq_el.get_text(" ", strip=True) if sq_el else ""501                if not sq_txt:502                    ic = cont.select_one(".nu-area")503                    if ic and ic.parent:504                        sq_txt = ic.parent.get_text(" ", strip=True)505                sv = _to_float(sq_txt)506                if sv and 80 <= sv <= 20000:507                    plan["sqft"] = sv508509                # prix : attribut structuré data-floorplan-price (« 2113 -2163 »),510                # sinon encadré « Starting at $2,113.00 /Month », sinon span Rent511                pv = None512                btn = cont.select_one("[data-floorplan-price]")513                if btn:514                    nums = [_to_float(x) for x in _NUM_RE.findall(515                        btn.get("data-floorplan-price") or "")]516                    nums = [n for n in nums if n and 100 <= n <= 20000]517                    if nums:518                        pv = min(nums)519                if pv is None:520                    rent_el = cont.select_one(521                        "span[data-selenium-id$='Rent']") \522                        or cont.select_one(".fieldset .font-weight-bold, "523                                           ".fieldset span.font-weight-bold")524                    if rent_el:525                        pv = _low_price(rent_el.get_text(" ", strip=True))526                if pv is None:527                    pv = _low_price(" ".join(528                        _PRICE_RE.findall(cont.get_text(" ", strip=True))))529                if pv:530                    plan["price"] = pv531532                if plan.get("name") or plan.get("price"):533                    plans.append(plan)534            except Exception:535                continue536        return plans537538539# =============================================================================540# Génération des sous-classes concrètes à partir du registre541# data/rentcafe_clients.json — une classe par client « ok », déposée dans les542# globals du module pour que connectors/__init__.py la découvre. Un registre543# absent/corrompu ne doit JAMAIS casser l'import du paquet (prod QC).544# =============================================================================545def _load_clients() -> list[dict]:546    try:547        with open(_REGISTRY_PATH, encoding="utf-8") as f:548            return json.load(f).get("clients") or []549    except (OSError, ValueError):550        return []551552553for _c in _load_clients():554    if (_c.get("status") or "") != "ok" or not _c.get("id"):555        continue556    _cls_name = "RC" + "".join(557        w.capitalize() for w in re.split(r"[^a-z0-9]+", _c["id"]) if w) \558        + "Connector"559    globals()[_cls_name] = type(_cls_name, (RentCafeClientConnector,), {560        "source_id": f"rc_{_c['id']}",561        "client": _c,562        "disabled": not _ONTARIO,563        "__doc__": f"Client RentCafe « {_c.get('name') or _c['id']} » "564                   f"({_c.get('regions') or 'Ontario'}) — généré depuis "565                   "data/rentcafe_clients.json.",566    })567del _c568
Files main
Menu

Theme