SPB Git

Repository Public

interrent.py 19.7 KB 506 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/interrent.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/interrent.py : connecteur InterRent REIT (irent.com)91#   Site Next.js (app router) : la page « communities/city/montreal » embarque92#   dans son flux RSC (self.__next_f.push) le JSON complet des communautés93#   (adresse, quartier, photos, commodités Amenities/Utilities, animaux94#   PetFriendly*, stationnement, contact, description via référence $NN)95#   avec leurs suites disponibles (type, chambres, sdb, pi², loyer, date).96#   Une seule requête suffit : le flux RSC embarque TOUTES les communautés97#   du REIT (QC, ON, BC), peu importe la ville demandée dans l'URL.98#   REIT pancanadien : filtre strict sur les villes du Grand Montréal.99#   Expansion Ontario 2026-08 — gaté LOUKA_ONTARIO : quand LOUKA_ONTARIO=1,100#   les communautés ON des marchés cibles (Toronto/GTA, Ottawa, Hamilton,101#   Kitchener-Waterloo) sont aussi conservées (province="ON", adresse102#   suffixée « ON »). Sans la variable, comportement strictement identique.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import html as htmllib107import json108import os109import re110111from ..schema import Listing, strip_accents112from .base import BaseConnector113114BASE = "https://www.irent.com"115CITY_URL = f"{BASE}/communities/city/montreal"116117# Expansion Ontario 2026-08 — gate : sans LOUKA_ONTARIO=1, QC seulement118_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"119120CHUNK_RE = re.compile(r'self\.__next_f\.push\(\[1,"((?:[^"\\]|\\.)*)"\]\)')121OBJ_START_RE = re.compile(r'\{"Id":\d+,"ImportId"')122123# Villes admissibles (Grand Montréal), clés sans accents/minuscules124_GM_CITIES = {125    "montreal": "Montréal",126    "cote-saint-luc": "Côte-Saint-Luc",127    "cote saint-luc": "Côte-Saint-Luc",128    "brossard": "Brossard",129    "laval": "Laval",130    "longueuil": "Longueuil",131    "verdun": "Montréal",132    "lasalle": "Montréal",133    "pointe-claire": "Pointe-Claire",134    "dollard-des-ormeaux": "Dollard-des-Ormeaux",135}136137# Villes admissibles en Ontario (expansion 2026-08, sous LOUKA_ONTARIO) :138# marchés cibles Toronto/GTA, Ottawa, Hamilton, Kitchener-Waterloo.139# clé sans accents/minuscules -> (ville normalisée, secteur imposé ou None) ;140# les anciens boroughs de Toronto/Ottawa sont repliés sur la ville fusionnée.141_ON_CITIES = {142    "toronto": ("Toronto", None),143    "etobicoke": ("Toronto", "Etobicoke"),144    "north york": ("Toronto", "North York"),145    "york": ("Toronto", "York"),146    "east york": ("Toronto", "East York"),147    "scarborough": ("Toronto", "Scarborough"),148    "mississauga": ("Mississauga", None),149    "brampton": ("Brampton", None),150    "markham": ("Markham", None),151    "vaughan": ("Vaughan", None),152    "richmond hill": ("Richmond Hill", None),153    "ajax": ("Ajax", None),154    "pickering": ("Pickering", None),155    "whitby": ("Whitby", None),156    "oshawa": ("Oshawa", None),157    "oakville": ("Oakville", None),158    "burlington": ("Burlington", None),159    "milton": ("Milton", None),160    "hamilton": ("Hamilton", None),161    "ottawa": ("Ottawa", None),162    "nepean": ("Ottawa", "Nepean"),163    "kanata": ("Ottawa", "Kanata"),164    "gloucester": ("Ottawa", "Gloucester"),165    "orleans": ("Ottawa", "Orléans"),166    "kitchener": ("Kitchener", None),167    "waterloo": ("Waterloo", None),168    "cambridge": ("Cambridge", None),169}170171_BED_TYPES = {0: "Studio", 1: "3½", 2: "4½", 3: "5½", 4: "6½"}172173174def _unescape_js(s: str) -> str:175    """Déséchappe une chaîne JS du flux RSC (\\" \\n \\uXXXX...)."""176    try:177        return json.loads(f'"{s}"')178    except ValueError:179        try:180            return (s.encode("latin-1", "backslashreplace")181                     .decode("unicode_escape"))182        except Exception:183            return s184185186def _clean(s: str) -> str:187    """Déséchappe les entités HTML répétées (&amp;amp;amp;...)."""188    s = s or ""189    for _ in range(4):190        t = htmllib.unescape(s)191        if t == s:192            break193        s = t194    return s.strip()195196197def _as_list(node) -> list:198    """Les nœuds XML->JSON du flux : dict simple ou liste."""199    if isinstance(node, list):200        return node201    if isinstance(node, dict):202        return [node]203    return []204205206def _strip_html(s: str) -> str:207    """HTML -> texte plat (entités déjà gérées par _clean)."""208    return _clean(re.sub(r"<[^>]+>", " ", s or ""))209210211# Références texte du flux RSC : « \nNN:Txxx, » suivi de xxx (hex) caractères.212_TEXT_REF_RE = re.compile(r"\n(\d+):T([0-9a-f]+),")213214215def _text_refs(blob: str) -> dict[str, str]:216    """Table des chaînes référencées « $NN » (descriptions d'immeubles…)."""217    refs: dict[str, str] = {}218    for m in _TEXT_REF_RE.finditer(blob):219        n = int(m.group(2), 16)220        refs[m.group(1)] = blob[m.end():m.end() + n]221    return refs222223224# Utilities (services inclus au bail) -> clés canoniques d'inclusions225def _utility_key(u: str) -> str | None:226    s = u.lower()227    if "hot water" in s:228        return "hot_water"229    if "heat" in s:230        return "heating"231    if "hydro" in s or "electric" in s:232        return "electricity"233    if "internet" in s:234        return "internet"235    if "cable" in s:236        return "cable"237    return None            # « Water » (eau froide) : pas de clé canonique238239240class InterrentConnector(BaseConnector):241    source_id = "interrent"242    request_delay = 0.6243    max_images = 20244245    def fetch(self) -> list[Listing]:246        page = self.get(CITY_URL).text247        blob = "".join(_unescape_js(c) for c in CHUNK_RE.findall(page))248249        # Objets communauté : {"Id":N,"ImportId":...,"PermaLink":...}250        communities: dict[int, dict] = {}251        pos = 0252        while True:253            m = OBJ_START_RE.search(blob, pos)254            if not m:255                break256            obj, end = self._read_object(blob, m.start())257            pos = end if end > m.start() else m.start() + 1258            if not obj or "PermaLink" not in obj or "Location" not in obj:259                continue260            cid = obj.get("Id")261            if isinstance(cid, int) and cid not in communities:262                communities[cid] = obj263264        refs = _text_refs(blob)265        listings: list[Listing] = []266        for c in communities.values():267            try:268                listings.extend(self._community_listings(c, refs))269            except Exception:270                continue271        return listings272273    @staticmethod274    def _read_object(blob: str, start: int) -> tuple[dict | None, int]:275        """Extrait un objet JSON par appariement d'accolades."""276        depth = 0277        in_str = False278        esc = False279        for i in range(start, min(len(blob), start + 400_000)):280            ch = blob[i]281            if in_str:282                if esc:283                    esc = False284                elif ch == "\\":285                    esc = True286                elif ch == '"':287                    in_str = False288                continue289            if ch == '"':290                in_str = True291            elif ch == "{":292                depth += 1293            elif ch == "}":294                depth -= 1295                if depth == 0:296                    try:297                        return json.loads(blob[start:i + 1]), i + 1298                    except ValueError:299                        return None, i + 1300        return None, start + 1301302    def _community_listings(self, c: dict,303                            refs: dict[str, str] | None = None) -> list[Listing]:304        refs = refs or {}305        loc = c.get("Location") or {}306        prov = (loc.get("ProvinceCode") or "").upper()307        raw_city = _clean(loc.get("City") or "")308        key = strip_accents(raw_city.lower()).strip()309        forced_sector = None310        if prov == "QC":311            city = _GM_CITIES.get(key)312            if not city:313                return []    # hors Grand Montréal314        elif prov == "ON" and _ONTARIO:315            # Expansion Ontario 2026-08 (gaté LOUKA_ONTARIO)316            city, forced_sector = _ON_CITIES.get(key, (None, None))317            if not city:318                return []    # hors marchés cibles ON319        else:320            return []321        sector = _clean(loc.get("Neighbourhood") or c.get("TagLine") or "")322        if strip_accents(sector.lower()) == strip_accents(city.lower()):323            sector = "" if city != "Montréal" else sector324        if prov == "QC" and key in ("cote-saint-luc", "verdun", "lasalle") \325                and not sector:326            sector = raw_city if city == "Montréal" else ""327        if forced_sector and not sector:328            sector = forced_sector    # ex. Etobicoke -> Toronto / Etobicoke329330        name = _clean(c.get("Name") or "")331        url = c.get("Url") or f"{BASE}/communities/{c.get('PermaLink', '')}"332        address = _clean(loc.get("Address") or "")333        postal = _clean(loc.get("PostalCode") or "")334        # adresse complète : suffixe « ON » pour l'Ontario (QC inchangé)335        last = f"ON {postal}".strip() if prov == "ON" else postal336        full_address = ", ".join(x for x in [address, city, last] if x)337338        # Photos de la communauté339        images: list[str] = []340        photos = (c.get("Photos") or {})341        for p in _as_list(photos.get("Photo") if isinstance(photos, dict)342                          else photos):343            u = (p or {}).get("Url") or ""344            if u.startswith("http") and u not in images:345                images.append(u)346        images = images[: self.max_images]347348        # Commodités : nœud Amenities.Amenity (liste) + services inclus349        am_node = (c.get("Amenities") or {})350        amenities = [_clean(str(a)) for a in351                     _as_list(am_node.get("Amenity") if isinstance(am_node, dict)352                              else am_node) if a]353        if not amenities:      # ancien champ, gardé en repli354            amenities = [a.strip() for a in355                         (c.get("amenities_TextField") or "").split(",")356                         if a.strip()]357        ut_node = (c.get("Utilities") or {})358        utilities = [_clean(str(u)) for u in359                     _as_list(ut_node.get("Utility") if isinstance(ut_node, dict)360                              else ut_node) if u]361        if utilities:362            amenities.append("Utilities included: " + ", ".join(utilities))363        amenities = amenities[:25]364365        # Détails structurés communs à la communauté366        details: dict = {}367        inclusions = {}368        for u in utilities:369            k = _utility_key(u)370            if k:371                inclusions[k] = True372        if inclusions:373            details["inclusions"] = inclusions374375        # Animaux : indicateurs PetFriendly* (structurés à la source)376        pets = None377        if c.get("PetFriendlyNotAllowed"):378            pets = "non"379        elif c.get("PetFriendly"):380            sub = [c.get("PetFriendlyCats"), c.get("PetFriendlySmallDogs"),381                   c.get("PetFriendlyLargeDogs")]382            pets = "conditions" if any(sub) and not all(sub) else "oui"383384        # Contact du bureau de location385        ci = c.get("ContactInformation") or {}386        contact = {}387        if ci.get("Phone"):388            contact["phone"] = _clean(ci["Phone"])389        if ci.get("Email"):390            contact["email"] = _clean(ci["Email"])391        if contact:392            details["contact"] = contact393394        # Stationnement : champ ParkingDetails (« Indoor Parking: $150 / month »)395        parking_txt = _strip_html(c.get("ParkingDetails") or "")396        if parking_txt:397            if re.search(r"no parking|not available", parking_txt, re.I):398                details["parking"] = {"available": False}399            else:400                parking: dict = {"available": True}401                indoor = re.search(r"indoor|interior|underground",402                                   parking_txt, re.I)403                outdoor = re.search(r"outdoor|exterior|surface",404                                    parking_txt, re.I)405                if indoor and not outdoor:406                    parking["type"] = "intérieur"407                elif outdoor and not indoor:408                    parking["type"] = "extérieur"409                prices = [float(p) for p in410                          re.findall(r"\$\s*(\d{2,4})", parking_txt)]411                if re.search(r"included|free", parking_txt, re.I):412                    parking["included"] = True413                elif prices:414                    parking["included"] = False415                    parking["price"] = min(prices)416                details["parking"] = parking417418        # Description de l'immeuble (référence $NN du flux RSC) + promo + animaux419        desc_ref = str(c.get("BuildingDescription") or "")420        building_desc = ""421        if desc_ref.startswith("$"):422            building_desc = _strip_html(refs.get(desc_ref[1:], ""))423        elif desc_ref:424            building_desc = _strip_html(desc_ref)425        promo = (c.get("Promotions") or {})426        promo_title = _clean(promo.get("Title") or "") \427            if isinstance(promo, dict) else ""428        pet_details = _strip_html(c.get("PetDetails") or "")429        extra_desc = " — ".join(x for x in [430            f"Promotion : {promo_title}" if promo_title else "",431            building_desc,432            f"Stationnement : {parking_txt}" if parking_txt else "",433            f"Animaux : {pet_details}" if pet_details else ""] if x)434435        suites = (c.get("Suites") or {})436        out: list[Listing] = []437        for s in _as_list(suites.get("Suite") if isinstance(suites, dict)438                          else suites):439            try:440                if (s.get("Available") or "").lower() != "yes":441                    continue442                type_name = _clean(s.get("TypeName") or "")443                # pseudo-unités « Promotional Price » sans numéro : ignorées444                if "promotional" in type_name.lower() and not s.get("Number"):445                    continue446                rate = s.get("Rate")447                price = float(rate) if isinstance(rate, (int, float)) \448                    and rate else None449                beds = s.get("Bedrooms")450                unit_type = _BED_TYPES.get(beds, "") \451                    if isinstance(beds, int) else ""452                sqft = s.get("SquareFeet")453                baths = s.get("Bathrooms")454                bits = []455                if sqft:456                    bits.append(f"{sqft} pi²")457                if baths:458                    bits.append(f"{baths} sdb")459                if type_name:460                    bits.append(f"plan {type_name}")461                suite_desc = _strip_html(s.get("Description") or "")462                if suite_desc:463                    bits.append(suite_desc)464                if extra_desc:465                    bits.append(extra_desc)466467                # plan d'étage en tête de galerie s'il existe468                imgs = list(images)469                fps = (s.get("Floorplans") or {})470                for fp in _as_list(fps.get("Floorplan")471                                   if isinstance(fps, dict) else fps):472                    fu = (fp or {}).get("Image") or ""473                    if fu.startswith("http") and fu not in imgs:474                        imgs.insert(0, fu)475476                num = s.get("Number") or ""477                label = f"{name} — {type_name}" if type_name else name478                if num:479                    label += f" (app. {num})"480                out.append(Listing(481                    source=self.source_id,482                    external_id=str(s.get("Id")),483                    url=url,484                    title=label,485                    address=full_address,486                    sector=sector,487                    city=city,488                    province=prov,489                    unit_type=unit_type,490                    price=price,491                    price_label=f"{int(rate)} $/mois" if price else "",492                    area_sqft=float(sqft) if isinstance(sqft, (int, float))493                    and 80 <= sqft <= 20000 else None,494                    availability=_clean(s.get("AvailabilityDate") or ""),495                    pets=pets,496                    description=" — ".join(bits)[:900],497                    amenities=list(amenities),498                    details=dict(details),499                    images=imgs[: self.max_images + 1],500                    lat=loc.get("Latitude"),501                    lng=loc.get("Longitude"),502                ))503            except Exception:504                continue505        return out506
Files main
Menu

Theme