SPB Git

Repository Public

hazelview.py 18.0 KB 442 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/hazelview.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# 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/hazelview.py : connecteur Hazelview Properties91#   (hazelviewproperties.com — ex-Timbercreek). Le site est rendu côté client92#   via l'API RentSync/LiftSystem (lift-api.rentsync.com/v2, client_id 497,93#   jeton public embarqué dans le JS du site). On interroge /v2/cities pour94#   les villes QC (toutes dans le Grand Montréal : Montréal, Verdun,95#   Côte-Saint-Luc, Pointe-Claire, Longueuil...), puis /v2/search par ville et96#   par nombre de chambres pour obtenir les types d'unités disponibles et leur97#   loyer. Une annonce par immeuble et par type d'unité. La page immeuble du98#   site (via cache BD) embarque un JSON complet (attribut data-locations de99#   la carte) : commodités, galerie photos, animaux détaillés, suites.100#   Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO=1 : on inclut TOUTES les101#   villes province_code=="ON" retournées par /v2/cities (Ottawa, GTA,102#   Hamilton, London, KW… selon les disponibilités du moment), sans whitelist103#   de villes — la whitelist Grand Montréal reste le garde-fou QC. Sans la104#   variable d'environnement, comportement strictement identique (prod QC).105# -----------------------------------------------------------------------------106from __future__ import annotations107108import html as htmllib109import json110import os111import re112113from bs4 import BeautifulSoup114115from ..schema import Listing, strip_accents116from .base import BaseConnector117118GALLERY = "https://assets.rentsync.com/timbercreek_communities/images/gallery/full/"119120API = "https://lift-api.rentsync.com/v2"121CLIENT_ID = "497"122AUTH_TOKEN = "sswpREkUtyeYjeoahA2i"    # jeton public (présent dans main.js)123124SEARCH_PARAMS = ("only_available_suites=true&show_all_properties=false"125                 "&min_bath=-1&max_bath=10&min_rate=0&max_rate=10000")126127# Expansion Ontario (gaté LOUKA_ONTARIO=1 ; prod QC intacte sans)128_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"129130# Villes QC admissibles (Grand Montréal) -> (ville, secteur imposé)131_GM_CITIES = {132    "montreal": ("Montréal", None),133    "verdun": ("Montréal", "Verdun"),134    "cote-saint-luc": ("Côte-Saint-Luc", None),135    "dollard-des-ormeaux": ("Dollard-des-Ormeaux", None),136    "pointe-claire": ("Pointe-Claire", None),137    "longueuil": ("Longueuil", None),138    "lasalle": ("Montréal", "LaSalle"),139}140141# (min_bed, max_bed, type d'unité)142_BED_QUERIES = [(0, 0, "Studio"), (1, 1, "3½"), (2, 2, "4½"),143                (3, 3, "5½"), (4, 5, "6½")]144_TAG_RE = re.compile(r"<[^>]+>")145146147def _pets_from_flags(d: dict) -> str | None:148    """Drapeaux animaux du JSON immeuble ('1'/'0'/None) -> oui/non/conditions."""149    def flag(k):150        v = d.get(k)151        return None if v in (None, "") else str(v) == "1"152    if flag("pets_not_allowed"):153        return "non"154    small, cats, large = (flag("pets_small_dogs"), flag("pets_cats"),155                          flag("pets_large_dogs"))156    if any(v for v in (small, cats, large)):157        # certains types refusés explicitement -> sous conditions158        if False in (small, cats, large):159            return "conditions"160        return "oui"161    if flag("pet_friendly"):162        return "oui"163    if flag("pet_friendly") is False:164        return "non"165    return None166167168class HazelviewConnector(BaseConnector):169    source_id = "hazelview"170    request_delay = 0.6171    max_cities = 10          # garde-fou (QC)172    max_cities_on = 40       # garde-fou distinct pour l'Ontario (gaté)173    max_details = 150        # garde-fou pages immeuble (vraies requêtes)174175    def _api(self, path: str, extra: str = "") -> list | dict:176        url = (f"{API}/{path}?client_id={CLIENT_ID}&auth_token={AUTH_TOKEN}"177               f"&locale=en{('&' + extra) if extra else ''}")178        return self.get(url).json()179180    def fetch(self) -> list[Listing]:181        cities = self._api("cities")182        qc = []183        on = []                      # villes ON (expansion, gaté LOUKA_ONTARIO)184        for c in cities if isinstance(cities, list) else []:185            code = (c.get("province_code") or "").upper()186            if code == "QC":187                key = strip_accents((c.get("city_name") or "").strip().lower())188                if key in _GM_CITIES:189                    qc.append((c.get("id"), key))190            elif _ONTARIO and code == "ON":191                # pas de whitelist : toutes les villes ON publiées par l'API192                name = (c.get("city_name") or "").strip()193                if name:194                    on.append((c.get("id"), name))195196        listings: list[Listing] = []197        bed_range: dict[str, tuple[int, int]] = {}198199        # (city_id, ville affichée, secteur imposé, province)200        targets = [(cid, *_GM_CITIES[key], "QC")201                   for cid, key in qc[: self.max_cities]]202        if _ONTARIO:203            targets += [(cid, name, None, "ON")204                        for cid, name in on[: self.max_cities_on]]205            # budget de pages immeuble élargi pour absorber le parc ON206            self.max_details = max(self.max_details, 400)207208        for city_id, city, forced_sector, province in targets:209            for min_bed, max_bed, unit_type in _BED_QUERIES:210                try:211                    props = self._api(212                        "search",213                        f"city_ids={city_id}&min_bed={min_bed}"214                        f"&max_bed={max_bed}&{SEARCH_PARAMS}&limit=50")215                except Exception:216                    continue217                if not isinstance(props, list):218                    continue219                for p in props:220                    try:221                        lst = self._prop_listing(p, unit_type, min_bed,222                                                 city, forced_sector,223                                                 province=province)224                        if lst:225                            listings.append(lst)226                            bed_range[lst.external_id] = (min_bed, max_bed)227                    except Exception:228                        continue229230        # Page immeuble du site (cache BD, 1 requête par immeuble) : le JSON231        # embarqué (data-locations) fournit commodités, galerie, animaux232        # détaillés et suites (superficie, date de disponibilité par unité)233        self._fetched = 0234        memo: dict[str, dict] = {}235        for lst in listings:236            pid = lst.external_id.split("-")[0]237            if not lst.url:238                continue239            if pid not in memo:240                key = f"{pid}|{lst.availability}|{lst.address}"241                try:242                    memo[pid] = self.detail(243                        pid, key, lambda u=lst.url: self._fetch_building(u))244                except Exception:245                    memo[pid] = {}246            mn, mx = bed_range.get(lst.external_id, (None, None))247            self._apply_building(lst, memo[pid], mn, mx)248        return listings249250    def _prop_listing(self, p: dict, unit_type: str, beds: int,251                      city: str, forced_sector: str | None,252                      province: str = "QC") -> Listing | None:253        if not p.get("availability_count"):254            return None255        addr = p.get("address") or {}256        stats = ((p.get("statistics") or {}).get("suites") or {})257        rates = stats.get("rates") or {}258        rmin, rmax = rates.get("min"), rates.get("max")259        sq = stats.get("square_feet") or {}260261        def _num(v):262            try:263                return float(v)264            except (TypeError, ValueError):265                return None266267        rmin, rmax = _num(rmin), _num(rmax)268        price = rmin269        if rmin and rmax and rmax != rmin:270            price_label = f"À partir de {int(rmin)} $ (max {int(rmax)} $)"271        elif rmin:272            price_label = f"{int(rmin)} $/mois"273        else:274            price_label = ""275276        sector = forced_sector or (addr.get("neighbourhood") or "").strip()277        details = p.get("details") or {}278        desc = _TAG_RE.sub(" ", details.get("overview") or "")279        desc = re.sub(r"\s+", " ", desc).strip()[:500]280        sbits = []281        sqmin, sqmax = _num(sq.get("min")), _num(sq.get("max"))282        if sqmin:283            sqtxt = (f"{int(sqmin)}-{int(sqmax)}"284                     if sqmax and sqmax != sqmin else f"{int(sqmin)}")285            sbits.append(f"{sqtxt} pi²")286        sbits.append(f"{p['availability_count']} unité(s) disponible(s)")287288        amenities = []289        feats = _TAG_RE.sub("|", details.get("features") or "")290        for f in feats.split("|"):291            f = f.strip()292            if 2 < len(f) < 60 and f not in amenities:293                amenities.append(f)294        amenities = amenities[:20]295296        images = []297        if p.get("photo_path"):298            images.append(p["photo_path"])299300        pid = p.get("id")301        name = (p.get("name") or "").strip()302        geo = p.get("geocode") or {}303        try:304            lat = float(geo.get("latitude"))305            lng = float(geo.get("longitude"))306        except (TypeError, ValueError):307            lat = lng = None308309        # champs structurés de l'API : animaux (bool), contact de location310        pets = None311        if isinstance(p.get("pet_friendly"), bool):312            pets = "oui" if p["pet_friendly"] else "non"313        details: dict = {}314        contact = p.get("contact") or {}315        cinfo: dict = {}316        if (contact.get("phone") or "").strip():317            cinfo["phone"] = contact["phone"].strip()318        for em in (contact.get("email") or "").split(","):319            em = em.strip()320            if em and "leadmanaging" not in em:      # relais de tracking exclu321                cinfo["email"] = em322                break323        if cinfo:324            details["contact"] = cinfo325326        return Listing(327            source=self.source_id,328            external_id=f"{pid}-{beds}bed",329            url=p.get("permalink") or "",330            title=f"{name} — {unit_type}",331            address=", ".join(x for x in [332                (addr.get("address") or "").strip(), city,333                "ON" if province == "ON" else "",334                (addr.get("postal_code") or "").strip()] if x),335            sector=sector,336            city=city,337            province=province,338            unit_type=unit_type,339            price=price,340            price_label=price_label,341            availability=(p.get("min_availability_date")342                          or p.get("availability_status_label") or ""),343            area_sqft=sqmin if sqmin else None,      # stats API (min du type)344            pets=pets,345            description=" — ".join([desc] + sbits if desc else sbits)[:600],346            amenities=amenities,347            details=details,348            images=images,349            lat=lat,350            lng=lng,351        )352353    # -- page immeuble du site (JSON embarqué data-locations) ------------------354    def _fetch_building(self, url: str) -> dict:355        """Extrait le JSON immeuble embarqué dans la page (widget carte) :356        commodités, services inclus, galerie, animaux détaillés, suites."""357        if self._fetched >= self.max_details:358            raise RuntimeError("budget de pages immeuble atteint")359        self._fetched += 1360        html = self.get(url).text361        soup = BeautifulSoup(html, "html.parser")362        el = soup.select_one("[data-locations]")363        if not el:364            return {}365        raw = el.get("data-locations") or ""366        try:367            data = json.loads(raw)368        except Exception:369            data = json.loads(htmllib.unescape(raw))370        node = (data[0] if isinstance(data, list) and data else {}) or {}371        d = node.get("data") or {}372        out: dict = {}373374        out["amenities"] = [a.get("name", "").strip()375                            for a in (d.get("Amenities") or [])376                            if a.get("name", "").strip()][:30]377        out["utilities"] = [u.get("name", "").strip()378                            for u in (d.get("Utilities") or [])379                            if isinstance(u, dict) and u.get("name", "").strip()]380        out["photos"] = [GALLERY + ph["image"]381                         for ph in (d.get("photos") or [])382                         if ph.get("image")][:15]383        out["pets_flags"] = {k: d.get(k) for k in384                             ("pet_friendly", "pets_small_dogs",385                              "pets_large_dogs", "pets_cats",386                              "pets_not_allowed") if d.get(k) is not None}387        out["pets_details"] = (d.get("pets_details") or "").strip()388        out["suites"] = [{389            "bed": s.get("bed"), "available": s.get("available"),390            "availability_date": s.get("availability_date"),391            "sq_ft": s.get("sq_ft"), "furnished": s.get("furnished"),392        } for s in (d.get("suites") or [])]393        return out394395    def _apply_building(self, lst: Listing, d: dict,396                        min_bed: int | None, max_bed: int | None) -> None:397        """Reporte le JSON immeuble (frais/cache) sur l'annonce."""398        if not d:399            return400        merged = list(dict.fromkeys(401            lst.amenities + (d.get("amenities") or []) +402            (d.get("utilities") or [])))403        if merged:404            lst.amenities = merged[:30]405        if d.get("photos"):406            lst.images = list(dict.fromkeys(lst.images + d["photos"]))[:15]407        pets = _pets_from_flags(d.get("pets_flags") or {})408        if pets:409            lst.pets = pets410411        # suites du type demandé : superficie et date précise si publiées412        suites = []413        for s in d.get("suites") or []:414            try:415                bed = int(s.get("bed"))416            except (TypeError, ValueError):417                continue418            if min_bed is None or not (min_bed <= bed <= (max_bed or min_bed)):419                continue420            if str(s.get("available")) == "1":421                suites.append(s)422        if suites:423            if lst.area_sqft is None:424                sqs = []425                for s in suites:426                    try:427                        v = float(s.get("sq_ft") or 0)428                    except (TypeError, ValueError):429                        v = 0430                    if v >= 80:431                        sqs.append(v)432                if sqs:433                    lst.area_sqft = min(sqs)434            dates = [s.get("availability_date") for s in suites435                     if s.get("availability_date")436                     and not str(s["availability_date"]).startswith("0000")]437            if dates and len(dates) == len(suites):438                # toutes les unités du type ont une date précise publiée439                lst.availability = min(dates)440            if all(str(s.get("furnished")) == "1" for s in suites):441                lst.furnished = True442
Files main
Menu

Theme