SPB Git

Repository Public

kw_urbain.py 16.1 KB 384 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/kw_urbain.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1914#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/kw_urbain.py : Keller Williams Urbain (kwurbain.ca)91#   Page /inscriptions rendue serveur : toutes les inscriptions de l'agence en92#   cartes HTML (plateforme marketingwebsites.ca, commune aux bureaux KW Canada).93#94#   ENRICHISSEMENT DÉTAIL (v3) : fiche /inscriptions/inscription/{id}/ rendue95#   serveur, thème « canvas » (différent du thème Charisma mais mêmes données96#   MW Properties). Structure réelle vérifiée (2026-08) :97#     - tableaux <tr><th>Libellé</th><td>Valeur</td> : Sommaire (superficie,98#       pièces, chambres, sdb, salles d'eau, année), Bâtiment (Type, Style,99#       Dimensions, terrain), Dépenses (taxes/coûts « $ 4857 / année »),100#       Caractéristiques (<th width="20%">) ;101#     - pièces : <td data-title="Pièce|Dimensions|Niveau|Revêtement"> ;102#     - description : <h3 class=title><span>Aperçu</span> + <div class=prop>103#       (p descriptif, p#addendum, p « Inclus :/Exclus : ») ;104#     - courtier : cartes .broker-card (h4 nom, h5 titre, lien tel:) ;105#     - GPS : initGoogleMap("streetMap", lat, lng) inline (commenté mais présent).106#   → property_type (« Type » du bloc Bâtiment) désormais rempli : c'est le107#   champ qui conditionne la publication (sinon quarantaine).108# -----------------------------------------------------------------------------109from __future__ import annotations110111import html as _html112import os113import re114115from .base import BaseConnector116from . import _detailutil as du117from ..normalize import parse_price118from ..schema import PropertyListing119120BASE = "https://www.kwurbain.ca"121LISTINGS = f"{BASE}/inscriptions/"122IMG_TMPL = "https://realestate.marketingwebsites.ca/property-images/{id}/{id}-{n:02d}.jpg"123# fiches détail (re)lues au plus par cycle — cache BD (key v3) : un cycle124# suffit pour les ~350 inscriptions, les suivants sont quasi gratuits125DETAIL_LIMIT = int(os.environ.get("IMMOKA_KW_DETAIL_LIMIT",126                                  os.environ.get("IMMOKA_DETAIL_LIMIT", "400")))127_KW_IMG_RE = re.compile(128    r'https://realestate\.marketingwebsites\.ca/property-images/\d+/[^"\'\\ ]+\.(?:jpg|jpeg|png|webp)',129    re.I)130_META_DESC_RE = re.compile(r'<meta\s+name="description"\s+content="([^"]{40,})"', re.I)131132_CARD_RE = re.compile(r'property-card mix property-(\d+)"(.*?)(?=property-card mix property-\d+"|</div>\s*</div>\s*</div>\s*</section>|$)', re.S)133_H5_RE = re.compile(r'<h5>(.*?)</h5>', re.S)134_PRICE_RE = re.compile(r'<span>(.*?)</span>', re.S)135_SUB_RE = re.compile(r'card-subtitle[^>]*>(.*?)</h6>', re.S)136_BED_RE = re.compile(r'fa-bed"></i>\s*(\d+)')137_BATH_RE = re.compile(r'fa-bath"></i>\s*(\d+)')138_STATUS_RE = re.compile(r'card-status[^>]*>(.*?)</div>', re.S)139140141def _txt(s: str) -> str:142    return _html.unescape(re.sub(r"<[^>]+>", "", s or "")).strip()143144145class KwUrbainConnector(BaseConnector):146    source_id = "kw_urbain"147    request_delay = 0.6148149    def fetch(self) -> list[PropertyListing]:150        html = self.get(LISTINGS).text151        listings: list[PropertyListing] = []152        for pid, block in _CARD_RE.findall(html):153            lst = self._to_listing(pid, block)154            if lst is not None:155                listings.append(lst)156        # fiche détail : galerie complète, description, caractéristiques157        # structurées, type de bien, pièces, courtier, GPS — cache BD.158        du.enrich(self, listings, DETAIL_LIMIT, parse_kw_detail, key="v3")159        return listings160161    def _to_listing(self, pid: str, block: str) -> PropertyListing | None:162        m_addr = _H5_RE.search(block)163        addr = _txt(m_addr.group(1)) if m_addr else ""164        m_price = _PRICE_RE.search(block)165        price_label = _txt(m_price.group(1)) if m_price else ""166        m_sub = _SUB_RE.search(block)167        sub = _txt(m_sub.group(1)) if m_sub else ""     # "Blainville, Laurentides J7B1M1"168        city = region = ""169        if sub:170            parts = [p.strip() for p in sub.split(",")]171            city = parts[0]172            if len(parts) > 1:173                # « Laurentides J7B1M1 » -> retirer le code postal174                region = re.sub(r"\s*[A-Z]\d[A-Z]\s?\d[A-Z]\d\s*$", "", parts[1]).strip()175        beds = _BED_RE.search(block)176        baths = _BATH_RE.search(block)177        return PropertyListing(178            source=self.source_id,179            external_id=pid,180            url=f"{BASE}/inscriptions/inscription/{pid}",181            title=addr,182            address=addr,183            city=city,184            region=region,185            price=parse_price(price_label),186            price_label=price_label,187            bedrooms=int(beds.group(1)) if beds else None,188            bathrooms=int(baths.group(1)) if baths else None,189            images=[IMG_TMPL.format(id=pid, n=1)],190            broker_name="Keller Williams Urbain",191        )192193194# --- fiche détail (MW Properties, thème « canvas » KW) ------------------------195# lignes <tr><th [width=20%]>Libellé</th><td>Valeur</td></tr> des 4 tableaux196# (Sommaire / Bâtiment / Dépenses / Caractéristiques) ; le tableau des pièces197# n'a pas de <th> par ligne (thead à 4 <th> consécutifs) → jamais capté ici.198_ROW_RE = re.compile(r'<tr>\s*<th(?:\s[^>]*)?>\s*([^<]+?)\s*</th>\s*'199                     r'<td[^>]*>\s*(.*?)\s*</td>\s*</tr>', re.S)200_ROOM_RE = re.compile(r'<td data-title="Pièce">([^<]*)</td>\s*'201                      r'<td data-title="Dimensions">([^<]*)</td>\s*'202                      r'<td data-title="Niveau">([^<]*)</td>\s*'203                      r'<td data-title="Revêtement">([^<]*)</td>', re.S)204# « Aperçu » : p descriptif + p#addendum + p « Inclus :/Exclus : »205_DESC_RE = re.compile(r'<h3 class="title">\s*<span>Aperçu</span>\s*</h3>\s*'206                      r'<div class="prop">(.*?)</div>', re.S | re.I)207_PARA_RE = re.compile(r'<p[^>]*>(.*?)</p>', re.S)208_BROKER_CARD_RE = re.compile(r'class="broker-card', re.I)209_NAME_RE = re.compile(r'card-title no-border">\s*([^<]+?)\s*</h4>')210_DESIG_RE = re.compile(r'card-subtitle no-border">\s*([^<]+?)\s*</h5>')211_TEL_RE = re.compile(r'href="tel:([^"]+)"')212_COORD_RE = re.compile(r'initGoogleMap\("(?:streetMap|map)",\s*'213                       r'(-?\d{1,2}\.\d+)\s*,\s*(-?\d{2,3}\.\d+)')214_TOUR_RE = re.compile(r'https?://(?:my\.matterport\.com/show/[^"\'\s<>]+'215                      r'|(?:www\.)?youtube\.com/(?:embed/|watch\?v=)[^"\'\s<>]+'216                      r'|youtu\.be/[^"\'\s<>]+'217                      r'|(?:player\.)?vimeo\.com/(?:video/)?\d+[^"\'\s<>]*)', re.I)218_ZEROS = {"", "0", "0x0", "0 x 0", "n/a", "-"}219220221def _text(fragment: str) -> str:222    """Fragment HTML -> texte propre (les <br> deviennent des sauts de ligne)."""223    t = re.sub(r'<br\s*/?>', '\n', fragment)224    t = re.sub(r'<[^>]+>', ' ', t)225    t = _html.unescape(t)226    t = re.sub(r'[ \t]+', ' ', t)227    return "\n".join(line.strip() for line in t.splitlines()).strip()228229230def _num(raw: str) -> float | None:231    v = raw.replace(" ", "").replace(" ", "").replace(" ", "")232    if v.count(",") == 1 and "." not in v:233        v = v.replace(",", ".")          # décimale française « 58,9 »234    else:235        v = v.replace(",", "")           # milliers « 2,966.53 »236    try:237        return float(v) or None238    except ValueError:239        return None240241242def _sqft(val: str) -> float | None:243    """« 2966.53 PC » / « 58.9 MC » -> pi² (unité obligatoire, 0 rejeté)."""244    m = re.search(r'([\d][\d\s  ,.]*)\s*(MC|M2|M²|PC|PI2|PI²)\b', val or "", re.I)245    if not m:246        return None247    v = _num(m.group(1))248    if not v:249        return None250    return round(v * 10.7639) if m.group(2).upper() in ("MC", "M2", "M²") else round(v)251252253def parse_kw_detail(html: str) -> dict:254    """Fiche KW (MW Properties) : galerie, description+addendum+inclusions,255    tableaux th/td (type de bien, année, superficies, taxes), pièces,256    courtier inscripteur, GPS, visite virtuelle."""257    out: dict = {}258    details: dict = {}259260    # galerie complète (property-images, ordre du document)261    seen, imgs = set(), []262    for u in _KW_IMG_RE.findall(html):263        if u not in seen:264            seen.add(u)265            imgs.append(u)266    if imgs:267        out["images"] = imgs268269    # tableaux Sommaire / Bâtiment / Dépenses / Caractéristiques270    for label, val in _ROW_RE.findall(html):271        label = _html.unescape(label).strip().rstrip(":").strip()272        val = re.sub(r'\s+', ' ', _text(val)).strip()273        if not label or val.lower() in _ZEROS:274            continue275        if label == "Type":276            out["property_type"] = val277            details.setdefault("Type de bâtiment", val)278        elif label == "Style":279            details.setdefault("Style", val)280        elif label == "Année de construction":281            if re.fullmatch(r"(1[6-9]|20)\d{2}", val):282                out["year_built"] = int(val)283                details.setdefault(label, val)284        elif label == "Superficie habitable":285            a = _sqft(val)286            if a:287                out["area_sqft"] = a288                details.setdefault(label, val)289        elif label == "Superficie du terrain":290            t = _sqft(val)291            if t:292                out["lot_sqft"] = t293                details.setdefault(label, val)294        elif label == "Dimensions":295            details.setdefault("Dimensions du bâtiment", val)296        elif label == "No. de pièces totales":297            if val.isdigit():298                details.setdefault("Nombre de pièces", val)299        elif label == "Chambres à coucher":300            if val.isdigit():301                out["bedrooms"] = int(val)302        elif label == "Salles de bain":303            if val.isdigit():304                out["bathrooms"] = int(val)305        elif label == "Salles d'eau":306            if val.isdigit():307                out["powder_rooms"] = int(val)308        else:309            # Dépenses (« Taxes municipales (2025) » -> « $ 4857 / année ») et310            # Caractéristiques (Proximité, Garage, Toiture, Zonage…)311            details.setdefault(label, val[:300])312313    # description « Aperçu » : p descriptif, p#addendum, p Inclus:/Exclus:314    md = _DESC_RE.search(html)315    if md:316        parts: list[str] = []317        for para in _PARA_RE.findall(md.group(1)):318            txt = _text(para)319            if not txt:320                continue321            low = txt.lower()322            if low.startswith("inclus"):323                details.setdefault("Inclusions",324                                   re.sub(r'^inclus\s*:\s*', '', txt, flags=re.I)[:600])325            elif low.startswith("exclus"):326                details.setdefault("Exclusions",327                                   re.sub(r'^exclus\s*:\s*', '', txt, flags=re.I)[:600])328            else:329                parts.append(txt)330        if parts:331            out["description"] = "\n\n".join(parts)[:6000]332    if not out.get("description"):333        mm = _META_DESC_RE.search(html)334        if mm:335            d = _html.unescape(mm.group(1)).strip()336            if d and not d.lower().startswith(("keller williams", "trouvez")):337                out["description"] = d338339    # détails de pièce -> features + nombre de pièces340    feats = []341    for name, dim, lvl, floor in _ROOM_RE.findall(html):342        name, dim = _html.unescape(name).strip(), _html.unescape(dim).strip()343        lvl, floor = _html.unescape(lvl).strip(), _html.unescape(floor).strip()344        if not name or name.lower() in _ZEROS:345            continue346        line = name + (f" — {dim}" if dim else "") + (f", {lvl}" if lvl else "")347        if floor:348            line += f" ({floor})"349        feats.append(line)350    if feats:351        out["features"] = feats[:40]352        details.setdefault("Nombre de pièces", str(len(feats)))353354    # courtier inscripteur : première carte .broker-card (nom, titre, tel)355    mb = _BROKER_CARD_RE.search(html)356    if mb:357        nxt = _BROKER_CARD_RE.search(html, mb.end())358        seg = html[mb.start():nxt.start() if nxt else mb.start() + 4000]359        mn = _NAME_RE.search(seg)360        if mn:361            out["broker_name"] = _html.unescape(mn.group(1)).strip()362        mdg = _DESIG_RE.search(seg)363        if mdg:364            details.setdefault("Titre du courtier", _html.unescape(mdg.group(1)).strip())365        mt = _TEL_RE.search(seg)366        if mt:367            out["broker_phone"] = _html.unescape(mt.group(1)).strip()368369    # coordonnées GPS (initGoogleMap inline, présent même commenté)370    mc = _COORD_RE.search(html)371    if mc:372        lat, lng = float(mc.group(1)), float(mc.group(2))373        if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:374            out["lat"], out["lng"] = lat, lng375376    # visite virtuelle / vidéo (matterport, youtube, vimeo)377    mt = _TOUR_RE.search(html)378    if mt:379        details.setdefault("Visite virtuelle / vidéo", mt.group(0))380381    if details:382        out["details"] = details383    return out384
Files main
Menu

Theme