SPB Git

Repository Public

immeubles_stuart.py 11.3 KB 286 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/immeubles_stuart.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-2313# Last Modified    : 2026-08-2314#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/immeubles_stuart.py : Les Immeubles Stuart (immeublesstuart.ca) —91#   agence indépendante de la Rive-Sud de Montréal (Saint-Lambert, Brossard,92#   Longueuil…), ~50 inscriptions en vente.93#94#   Site WordPress propulsé par la plateforme « Ma Clé » (photos sur95#   maclebrokers-photos.s3.amazonaws.com). Liste /proprietes/ rendue serveur,96#   une seule page : cartes <article class="propriete-card"> (data-ville,97#   data-prix, adresse, MLS Centris, chambres/salles de bain). On ne garde que98#   les URLs « -a-vendre » (les « -a-louer » sont des locations).99#100#   Fiche détail : JSON-LD RealEstateListing très riche avec extensions mc:*101#   (caractéristiques, taxes, évaluations, inclusions/exclusions, addenda,102#   agent nom/téléphone) + galerie S3 ({mls}{n}.jpg — exclure photo_membre).103#   Pas de GPS sur la fiche (code postal seulement). Enrichissement du.enrich.104#105#   Agence première main (pas d'infixe _ag_) : ses fiches battent les copies106#   portails au même n° Centris dans la dédup.107# -----------------------------------------------------------------------------108from __future__ import annotations109110import html as _html111import json112import os113import re114115from .base import BaseConnector116from . import _detailutil as du117from ..normalize import parse_price118from ..schema import PropertyListing119120SITE = "https://immeublesstuart.ca"121LIST_URL = SITE + "/proprietes/"122AGENCY = "Les Immeubles Stuart"123DETAIL_LIMIT = int(os.environ.get("IMMOKA_STUART_DETAIL_LIMIT", "120"))124125_CARD_SPLIT = re.compile(r'<article class="propriete-card')126_HREF_RE = re.compile(r'href="(https?://immeublesstuart\.ca/proprietes/[^"]*--(\d{6,10})/?)"')127_VILLE_RE = re.compile(r'data-ville="([^"]*)"')128_PRIX_RE = re.compile(r'data-prix="(\d+)"')129_ADRESSE_RE = re.compile(r'propriete-card-adresse">([^<]+)<')130_META_RE = re.compile(r'<li>\s*(\d+)\s+(chambre|salle)', re.I)131_IMG_RE = re.compile(r'src="(https://maclebrokers-photos\.s3\.amazonaws\.com/[^"]+)"')132_S3_RE = re.compile(r'https://maclebrokers-photos\.s3\.amazonaws\.com/(?:large_)?photo/[^"\'\s]+\.jpe?g', re.I)133134135class ImmeublesStuartConnector(BaseConnector):136    source_id = "stuart"137    request_delay = 0.4138139    def fetch(self) -> list[PropertyListing]:140        html = self.get(LIST_URL).text141        by_id: dict[str, PropertyListing] = {}142        for blk in _CARD_SPLIT.split(html)[1:]:143            blk = blk[:4000]144            hm = _HREF_RE.search(blk)145            if not hm or "-a-vendre" not in hm.group(1):146                continue147            mls = hm.group(2)148            city = _html.unescape((_VILLE_RE.search(blk) or [None, ""])[1]).strip()149            am = _ADRESSE_RE.search(blk)150            address = _html.unescape(am.group(1)).strip() if am else ""151            pm = _PRIX_RE.search(blk)152            price = int(pm.group(1)) if pm else None153            beds = baths = None154            for n, kind in _META_RE.findall(blk):155                if kind.lower() == "chambre":156                    beds = int(n)157                else:158                    baths = int(n)159            im = _IMG_RE.search(blk)160            by_id.setdefault(mls, PropertyListing(161                source=self.source_id, external_id=mls,162                url=hm.group(1),163                title=f"Propriété à vendre — {address or city}".strip(" —"),164                address=address, city=city,165                price=price,166                price_label=(f"{price:,} $".replace(",", " ") if price else ""),167                bedrooms=beds, bathrooms=baths, mls=mls,168                images=[im.group(1)] if im else [],169                agency=AGENCY, broker_name=AGENCY,170            ))171        listings = list(by_id.values())172        du.enrich(self, listings, DETAIL_LIMIT, _parse_detail, key="v1")173        for lst in listings:   # titre enrichi une fois le type connu174            if lst.property_type and lst.title.startswith("Propriété à vendre"):175                lst.title = f"{lst.property_type} à vendre — {lst.address or lst.city}".strip(" —")176        return listings177178179def _parse_detail(html: str) -> dict:180    """Fiche Ma Clé : JSON-LD RealEstateListing + extensions mc:* + galerie S3."""181    node = None182    for n in du.ld_nodes(html):183        if n.get("@type") == "RealEstateListing":184            node = n185            break186    if node is None:187        return {}188    out: dict = {}189    details: dict = {}190    features: list[str] = []191192    desc = _html.unescape(str(node.get("description") or "")).strip()193    addenda = _html.unescape(str(node.get("mc:addenda") or "")).strip()194    if addenda and addenda not in desc:195        desc = (desc + "\n\n" + addenda).strip()196    if desc:197        out["description"] = desc198199    addr = node.get("address") or {}200    if isinstance(addr, dict):201        if addr.get("streetAddress"):202            out["address"] = str(addr["streetAddress"]).strip()203        if addr.get("addressLocality"):204            out["city"] = str(addr["addressLocality"]).strip()205        if addr.get("postalCode"):206            details["Code postal"] = str(addr["postalCode"]).strip()207208    offers = node.get("offers") or {}209    if isinstance(offers, dict) and offers.get("price"):210        try:211            out["price"] = float(offers["price"])212        except (TypeError, ValueError):213            pass214215    if node.get("yearBuilt"):216        ym = re.search(r"\b(1[6-9]\d{2}|20\d{2})\b", str(node["yearBuilt"]))217        if ym:218            out["year_built"] = int(ym.group(1))219            details["Année de construction"] = ym.group(1)220221    lot = node.get("lotSize") or {}222    if isinstance(lot, dict) and lot.get("value"):223        try:224            sq = float(lot["value"])225            if str(lot.get("unitCode") or "FTK").upper() == "MTK":226                sq *= 10.7639227            out["lot_sqft"] = round(sq, 1)228        except (TypeError, ValueError):229            pass230231    if node.get("mc:type"):232        out["property_type"] = str(node["mc:type"]).strip()233        details["Type de propriété"] = out["property_type"]234235    car = node.get("mc:caracteristiques")236    if isinstance(car, dict):237        for k, v in car.items():238            k, v = str(k).strip(), str(v).strip()239            if k and v:240                details[k] = v241                features.append(f"{k} : {v}" if len(v) < 40 else k)242243    for src, dst in (("mc:inclusions", "Inclusions"),244                     ("mc:exclusions", "Exclusions"),245                     ("mc:eval_batiment", "Évaluation municipale (bâtiment)"),246                     ("mc:eval_terrain", "Évaluation municipale (terrain)"),247                     ("mc:eval_annee", "Évaluation municipale (année)")):248        v = node.get(src)249        if v not in (None, ""):250            v = str(v).strip()251            if dst.startswith("Évaluation") and v.isdigit():252                v = f"{int(v):,} $".replace(",", " ")253            details[dst] = v254    taxes = node.get("mc:taxes")255    if isinstance(taxes, list) and taxes:256        details["Taxes"] = " ; ".join(str(t).strip() for t in taxes if t)257258    agent = node.get("agent") or {}259    if isinstance(agent, dict):260        if agent.get("name"):261            out["broker_name"] = str(agent["name"]).strip()262        tel = str(agent.get("telephone") or "").strip()263        if re.fullmatch(r"\d{10}", tel):264            tel = f"{tel[:3]} {tel[3:6]}-{tel[6:]}"265        if tel:266            out["broker_phone"] = tel267268    # galerie S3 : {mls}{n}.jpg (large_photo + photo), photo_membre = portraits269    mls = str(node.get("mc:no_inscription") or "")270    imgs, seen = [], set()271    for u in _S3_RE.findall(html):272        name = u.rsplit("/", 1)[-1]273        if mls and not name.startswith(mls):274            continue275        if name not in seen:276            seen.add(name)277            imgs.append(u)278    if imgs:279        out["images"] = imgs280281    if details:282        out["details"] = details283    if features:284        out["features"] = features285    return out286
Files main
Menu

Theme