SPB Git

Repository Public

loftsmtl.py 12.1 KB 323 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/loftsmtl.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/loftsmtl.py : connecteur Lofts MTL (loftsmtl.com)91#   Lofts et appartements — Mile End, Plateau, Vieux-Montréal,92#   Ville Mont-Royal. Plateforme Rentsync/LiftSystem : l'inventaire des93#   immeubles vient de l'API publique api.theliftsystem.com (client_id 773,94#   jeton public embarqué dans le site), puis chaque page immeuble95#   (rendu serveur) expose les unités disponibles (div.suite : type, prix,96#   pi², photos, disponibilité) et la section « Amenities » (commodités de97#   l'unité et de l'immeuble). L'API fournit aussi lat/lng, code postal,98#   pet_friendly (booléen) et le téléphone du gestionnaire.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type107from .base import BaseConnector108109SITE = "https://www.loftsmtl.com"110API_URL = ("https://api.theliftsystem.com/v2/search"111           "?locale=en&client_id=773&auth_token=sswpREkUtyeYjeoahA2i"112           "&show_all_properties=true&limit=200")113114# Villes de la région de Montréal telles que renvoyées par l'API115_CITY_MAP = {116    "montréal": "Montréal", "montreal": "Montréal",117    "mont-royal": "Mont-Royal", "mount royal": "Mont-Royal",118    "westmount": "Westmount", "outremont": "Montréal",119}120121122def _suite_type(raw: str) -> str:123    s = (raw or "").strip().lower()124    if "studio" in s or "loft" in s and not re.search(r"\d", s):125        return "Studio" if "studio" in s else "Loft"126    m = re.search(r"(\d)\s*(?:1/2|½)", s)127    if m:128        return f"{m.group(1)}½"129    m = re.search(r"(\d)\s*bed", s)130    if m:131        return {0: "Studio", 1: "3½", 2: "4½", 3: "5½"}.get(132            int(m.group(1)), f"{m.group(1)} chambres")133    return normalize_unit_type(raw)134135136def _parse_price_us(raw: str) -> float | None:137    m = re.search(r"\$\s*([\d,\s]+(?:\.\d{2})?)", raw or "")138    if not m:139        return None140    try:141        val = float(m.group(1).replace(",", "").replace(" ", "").replace(" ", ""))142    except ValueError:143        return None144    return val if 100 <= val <= 20000 else None145146147def _strip_html(raw: str) -> str:148    return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", raw or "")).strip()149150151class LoftsMtlConnector(BaseConnector):152    source_id = "loftsmtl"153    request_delay = 0.6154    max_buildings = 25       # garde-fou155156    def fetch(self) -> list[Listing]:157        listings: list[Listing] = []158        try:159            buildings = self.get(API_URL).json()160        except Exception:161            return listings162        if not isinstance(buildings, list):163            return listings164165        for i, b in enumerate(buildings):166            if i >= self.max_buildings:167                break168            try:169                listings.extend(self._building_listings(b))170            except Exception:171                continue172        return listings173174    # -- une page immeuble -> annonces par unité disponible ---------------------175    def _building_listings(self, b: dict) -> list[Listing]:176        addr = b.get("address") or {}177        raw_city = (addr.get("city") or "").strip()178        city = _CITY_MAP.get(raw_city.lower())179        if not city:180            return []                    # hors région de Montréal181        sector = (addr.get("neighbourhood") or "").strip()182        if sector.lower() == "town of mount royal":183            sector = "" if city == "Mont-Royal" else sector184        bid = b.get("id")185        name = (b.get("name") or "").strip()186        address = (addr.get("address") or "").strip()187        postal = (addr.get("postal_code") or "").strip()188        if postal:189            address = f"{address}, {postal}" if address else postal190        permalink = (b.get("permalink") or "").strip() or SITE191        desc = _strip_html((b.get("details") or {}).get("overview", ""))[:600]192193        # lat/lng structurés de l'API194        geo = b.get("geocode") or {}195        try:196            lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))197        except (TypeError, ValueError):198            lat = lng = None199200        # politique animaux structurée de l'API201        pf = b.get("pet_friendly")202        pets = {True: "oui", False: "non"}.get(pf)203204        # téléphone du gestionnaire (structuré)205        phone = ((b.get("contact") or {}).get("phone")206                 or (b.get("client") or {}).get("phone") or "").strip()207208        # La page immeuble sert /apartments/<slug> ou /residential/<slug>209        html = ""210        for url in (permalink,211                    permalink.replace("/apartments/", "/residential/")):212            try:213                html = self.get(url).text214                break215            except Exception:216                continue217        if not html:218            return []219        soup = BeautifulSoup(html, "html.parser")220221        # section « Amenities » : commodités de l'unité + de l'immeuble222        bldg_amenities: list[str] = []223        for holder in soup.select(".amenities .amenity-holder"):224            label = " ".join(holder.get_text(" ", strip=True).split())225            if label and label not in bldg_amenities:226                bldg_amenities.append(label)227228        results: list[Listing] = []229        for suite in soup.select("div.suite"):230            try:231                lst = self._parse_suite(suite, b, city, sector, name,232                                        address, permalink, desc,233                                        bldg_amenities, lat, lng, pets, phone)234            except Exception:235                continue236            if lst:237                results.append(lst)238        return results239240    def _parse_suite(self, suite, b, city, sector, name, address,241                     permalink, desc, bldg_amenities, lat, lng, pets,242                     phone) -> Listing | None:243        type_el = suite.select_one(".suite-type")244        if not type_el:245            return None246        raw_type = type_el.get_text(" ", strip=True)247        num_el = suite.select_one(".suite-number")248        number = num_el.get_text(" ", strip=True) if num_el else ""249250        rate_el = suite.select_one(".suite-rate .value") or \251            suite.select_one(".suite-rate")252        price_label = rate_el.get_text(" ", strip=True) if rate_el else ""253        price = _parse_price_us(price_label)254255        sqft_el = suite.select_one(".suite-sqft .value")256        sqft = sqft_el.get_text(strip=True) if sqft_el else ""257        bath_el = suite.select_one(".suite-bath .value")258        baths = bath_el.get_text(strip=True) if bath_el else ""259260        avail_el = suite.select_one(".suite-availability")261        availability = avail_el.get_text(" ", strip=True) if avail_el else ""262        availability = re.sub(r"^Availab\w*\s*", "", availability).strip()263264        photos = [a.get("href") for a in suite.select("a.suite-photo")265                  if a.get("href")]266        photos = list(dict.fromkeys(photos))[:30]267268        # id stable : rel="suite-995148-photos" sinon immeuble+numéro269        sid = ""270        first = suite.select_one("a.suite-photo[rel]")271        if first:272            rel = first.get("rel") or ""273            if isinstance(rel, (list, tuple)):274                rel = " ".join(rel)275            m = re.match(r"suite-(\d+)", rel)276            if m:277                sid = m.group(1)278        ext_id = sid or f"{b.get('id')}-{re.sub(r'[^0-9A-Za-z-]', '', number)}"279280        amenities = []281        if baths:282            amenities.append(f"{baths} salle(s) de bain")283        if sqft and sqft != "0":284            amenities.append(f"{sqft} pi²")285        for label in bldg_amenities:286            if label not in amenities:287                amenities.append(label)288289        # superficie structurée (cellule .suite-sqft de la page immeuble)290        area_sqft = None291        try:292            v = float(sqft.replace(",", ""))293            if v >= 80:294                area_sqft = v295        except (AttributeError, ValueError):296            pass297298        details: dict = {}299        if phone:300            details["contact"] = {"phone": phone}301302        return Listing(303            source=self.source_id,304            external_id=str(ext_id),305            url=permalink,306            title=f"{name} — unité {number}" if number else name,307            address=address,308            sector=sector,309            city=city,310            unit_type=_suite_type(raw_type),311            price=price,312            price_label=f"{price_label}/mo" if price_label else "",313            availability=availability or "Disponible",314            area_sqft=area_sqft,315            pets=pets,316            description=desc,317            amenities=amenities,318            details=details,319            images=photos,320            lat=lat,321            lng=lng,322        )323
Files main
Menu

Theme