SPB Git

Repository Public

accommod8u.py 14.8 KB 353 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/accommod8u.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/accommod8u.py : connecteur Accommod8u (accommod8u.com)91#   Gros gestionnaire de Waterloo ON (~10 immeubles/villages au moment de92#   l'écriture : tours Albert/Lester/Sunview, THE LINQ, villages étudiants93#   Linden/Spring/Walnut au bail mensuel — longue durée, donc pertinent).94#   Site « corporate » Yardi RentCafe derrière Cloudflare : curl nu = 403,95#   Scrapfly asp=true suffit (rendu serveur, PAS de render_js). Comme Killam,96#   la page /residential/apartments embarque TOUT le portefeuille dans97#   l'input caché `#available_prop` (JSON doublement encodé) : nom, adresse,98#   ville/ON/code postal, lat/lng, fourchette de loyer, politique animaux,99#   téléphone, vignette, occupation et l'URL du MICROSITE RentCafe de chaque100#   immeuble (apartments-waterloo-228albert.com…).101#   La page /floorplans du microsite (même anti-bot, via self.detail() +102#   Scrapfly) donne les cartes plans d'étage : « N Bed / N Bath / N Sq. Ft. /103#   Starting at $X /Month » quand des unités sont disponibles, « Call for104#   details » sinon (carte sans lien « Availability » → écartée, rien105#   d'inventé). Une annonce PAR PLAN D'ÉTAGE DISPONIBLE, avec repli « une106#   annonce par immeuble » (loyer plancher du flux) si aucune carte n'a de107#   prix mais que l'immeuble n'est pas complet. Les villages étudiants108#   affichent des loyers à la chambre (~600 $) : le nom du plan (« Room »,109#   « 4 Bedroom »…) donne le type d'unité, jamais de valeur inventée.110#   Immeubles IsFullyOccupied (ex. « Fir Village (Fully Leased) ») : ignorés.111#   Expansion Ontario — gaté LOUKA_ONTARIO=1 : sans la variable, disabled.112# -----------------------------------------------------------------------------113from __future__ import annotations114115import hashlib116import json117import os118import re119120from bs4 import BeautifulSoup121122from ..schema import Listing, normalize_unit_type, strip_accents123from .base import BaseConnector124125BASE = "https://www.accommod8u.com"126SEARCH_PAGE = f"{BASE}/residential/apartments"127128# Gate expansion Ontario : hors registre tant que LOUKA_ONTARIO=1 absent129_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"130131# blob JSON du portefeuille (input caché RentCafe, doublement encodé)132_PROP_BLOB_RE = re.compile(r"id=\"available_prop\"\s+value='(.*?)'", re.S)133134# cartes plans d'étage du microsite : « 1 Bed », « 2 Bath », « 660 Sq. Ft. »135_BED_RE = re.compile(r"([\d.]+)\s*Bed\b")136_BATH_RE = re.compile(r"([\d.]+)\s*Bath")137_SQFT_RE = re.compile(r"([\d,]+)(?:-\s*to\s*[\d,]+)?\s*Sq\.?\s*Ft", re.I)138_PRICE_RE = re.compile(r"\$\s*([\d,]+(?:\.\d{2})?)")139140141class Accommod8uConnector(BaseConnector):142    source_id = "accommod8u"143    request_delay = 1.5       # tout passe par Scrapfly ASP : rester très poli144    disabled = not _ONTARIO   # gate expansion Ontario (LOUKA_ONTARIO=1)145    max_properties = 20       # garde-fou (10 immeubles au 2026-08)146    max_images = 15147148    # -- portefeuille : blob embarqué de la page de recherche --------------------149    def _properties(self) -> list[dict]:150        page = self.get_scrapfly(SEARCH_PAGE, render_js=False, asp=True)151        m = _PROP_BLOB_RE.search(page or "")152        if not m:153            raise RuntimeError("Accommod8u : blob #available_prop introuvable "154                               "(gabarit RentCafe modifié ou échec ASP)")155        return json.loads(json.loads(m.group(1)))156157    def fetch(self) -> list[Listing]:158        listings: list[Listing] = []159        count = 0160        for p in self._properties():161            if (p.get("propertyState") or "").strip().upper() != "ON":162                continue163            if p.get("IsFullyOccupied") is True:164                continue          # complet (« Fully Leased ») : rien à publier165            if count >= self.max_properties:166                break167            count += 1168            try:169                listings.extend(self._listings(p))170            except Exception:171                continue172        return listings173174    # -- annonces d'un immeuble (une par plan d'étage disponible) ----------------175    def _listings(self, p: dict) -> list[Listing]:176        pid = str(p.get("propertyid"))177        name = (p.get("propertyName") or "").strip()178        # microsite RentCafe de l'immeuble (sans le paramètre de tracking)179        site = ((p.get("PropertySiteUrl") or p.get("LinkUrl") or "")180                .split("?")[0].rstrip("/"))181        url = f"{site}/floorplans" if site.startswith("http") else SEARCH_PAGE182183        city = (p.get("propertyCity") or "").strip()184        street = (p.get("propertyAddress") or "").strip()185        postal = (p.get("propertyZipCode") or "").strip()186        address = ", ".join(x for x in (street, city) if x) + ", ON"187        if postal:188            address += f" {postal}"189190        try:191            lat = float(p.get("propertyLat")) or None192            lng = float(p.get("propertyLng")) or None193        except (TypeError, ValueError):194            lat = lng = None195196        # politique animaux structurée du flux197        pets = None198        try:199            pol = p.get("bPetPolicy") or {}200            if isinstance(pol, str):201                pol = json.loads(pol)202            if pol.get("bNoPetsAllowed") is True:203                pets = "non"204            elif pol.get("bCats") and pol.get("bDogs"):205                pets = "oui"206            elif pol.get("bCats") or pol.get("bDogs"):207                pets = "conditions"208        except (ValueError, TypeError):209            pass210211        details: dict = {}212        if (p.get("phone") or "").strip():213            details["contact"] = {"phone": p["phone"].strip()}214215        # page /floorplans du microsite via le cache BD : revisitée seulement216        # quand la ligne du flux change (loyers, occupation, vignette)217        feed_key = hashlib.sha1("|".join(str(p.get(k)) for k in (218            "propertyMinRent", "propertyMaxRent", "propertyMinBed",219            "propertyMaxBed", "IsFullyOccupied", "dtMinUnitAvailable",220            "propertyThumb", "PropertySiteUrl",221        )).encode("utf-8")).hexdigest()222        d = self.detail(pid, feed_key, lambda: self._fetch_floorplans(url))223224        thumb = (p.get("propertyThumb") or "").strip()225        base_images = [thumb] if thumb else []226227        common = dict(228            source=self.source_id, url=url, address=address, city=city,229            province="ON", pets=pets, lat=lat, lng=lng,230        )231232        out: list[Listing] = []233        for fp in d.get("floorplans") or []:234            if fp.get("price") is None:235                continue    # « Call for details » sans lien Availability :236                # aucune unité annoncée disponible — rien d'inventé237            images = [u for u in base_images + (fp.get("images") or [])238                      if u][: self.max_images]239            beds = fp.get("beds")240            slug = re.sub(r"[^a-z0-9]+", "-",241                          strip_accents((fp.get("name") or "").lower())242                          ).strip("-")243            out.append(Listing(244                external_id=f"{pid}-{slug or 'u'}",245                title=f"{name} — {fp['name']}" if fp.get("name") else name,246                unit_type=self._unit_type(fp.get("name") or "", beds),247                bedrooms=beds,248                bathrooms=fp.get("baths"),249                price=fp["price"],250                price_label=f"À partir de {fp['price']:.0f} $ /mois",251                availability="Unités disponibles",252                area_sqft=fp.get("sqft"),253                details=dict(details),254                images=images,255                **common,256            ))257        if out:258            return out259260        # repli : une annonce par immeuble avec le loyer plancher du flux261        price = None262        try:263            price = float(p.get("propertyMinRent") or 0) or None264        except (TypeError, ValueError):265            pass266        if price is None:267            return []      # ni plan disponible ni loyer affiché : rien268        beds = None269        try:270            bmin = float(p.get("propertyMinBed") or -1)271            if bmin >= 0 and bmin == float(p.get("propertyMaxBed") or -1):272                beds = bmin273        except (TypeError, ValueError):274            pass275        return [Listing(276            external_id=pid,277            title=name,278            unit_type=("Studio" if beds == 0 else normalize_unit_type(279                f"{int(beds)} chambres") if beds is not None else ""),280            bedrooms=beds,281            price=price,282            price_label=f"À partir de {price:.0f} $ /mois",283            availability="Unités disponibles",284            details=details,285            images=base_images[: self.max_images],286            **common,287        )]288289    @staticmethod290    def _unit_type(fp_name: str, beds: float | None) -> str:291        """Type d'unité : nom du plan (« Room » -> Chambre) sinon dérivé cc."""292        ut = normalize_unit_type(fp_name)293        if ut and ut != fp_name.strip():294            return ut295        if beds == 0:296            return "Studio"297        if beds is not None:298            return normalize_unit_type(f"{int(beds)} chambres")299        return ut300301    # -- page /floorplans du microsite RentCafe ----------------------------------302    def _fetch_floorplans(self, url: str) -> dict:303        out: dict = {"floorplans": []}304        if not url.startswith("http"):305            return out306        try:307            page = self.get_scrapfly(url, render_js=False, asp=True)308        except Exception:309            return out310        if not page:311            return out312        soup = BeautifulSoup(page, "html.parser")313        seen: set[str] = set()314        for card in soup.select(".fp-container"):315            txt = card.get_text(" ", strip=True)316            h = card.find(["h2", "h3", "h4"])317            fp_name = h.get_text(" ", strip=True) if h else ""318            if not fp_name:319                # premier segment avant « N Bed » (gabarit compact)320                fp_name = re.split(r"\d+\s*Bed", txt)[0].strip()321            if not fp_name or fp_name.lower() in seen:322                continue323            seen.add(fp_name.lower())324            mb = _BED_RE.search(txt)325            mba = _BATH_RE.search(txt)326            msq = _SQFT_RE.search(txt)327            sqft = float(msq.group(1).replace(",", "")) if msq else None328            # prix seulement si des unités sont disponibles (lien Availability)329            price = None330            has_avail = card.find(331                "a", href=re.compile(r"/floorplans/")) is not None332            mp = _PRICE_RE.search(txt)333            if mp and has_avail:334                price = float(mp.group(1).replace(",", ""))335            images = []336            for img in card.find_all("img"):337                src = (img.get("src") or img.get("data-src") or "").strip()338                if src and "resource.rentcafe.com" in src \339                        and src not in images:340                    src = re.sub(r"c_l(?:fill|imit),w_\d+(?:,h_\d+)?",341                                 "c_limit,w_1200", src)342                    images.append(src)343            out["floorplans"].append({344                "name": fp_name,345                "beds": (float(mb.group(1)) if mb346                         else 0.0 if "Studio" in txt else None),347                "baths": float(mba.group(1)) if mba else None,348                "sqft": sqft if sqft and 80 <= sqft <= 20000 else None,349                "price": price,350                "images": images[:5],351            })352        return out353
Files main
Menu

Theme