SPB Git

Repository Public

vendre_ca.py 11.7 KB 285 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/vendre_ca.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1313# Last Modified    : 2026-09-0614#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/vendre_ca.py : Vendre.ca (portail hybride courtiers + vendeurs privés)91#92#   Portail québécois (~9 500 fiches) mêlant inscriptions de courtiers (avec93#   n° MLS/Centris) et vendeurs privés. Énumération EXHAUSTIVE via les 494#   sitemaps de catégorie (res/mpx/com/lnd) : l'URL FR encode type, ville,95#   adresse et le VID (identifiant Vendre.ca). La fiche détail (JSON-LD96#   Place + RealEstateListing + Offer) fournit adresse exacte, géoloc, prix,97#   année, courtier, description et le n° MLS ; galerie cloud.vendre.ca (_lrg).98#99#   source_id « vendre_ag_ca » : l'infixe _ag_ active la déduplication Centris100#   (db.refresh_dedup). Quand le n° MLS est connu, il devient l'external_id —101#   les fiches déjà portées par la bannière du courtier (RE/MAX, Royal LePage…)102#   sont masquées ; les fiches uniques (vendeurs privés = VID, courtiers non103#   couverts) restent visibles. Aucun double-comptage.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import html as _html108import json109import os110import re111112import requests113114from .base import BaseConnector115from . import _detailutil as du116from ..normalize import normalize_property_type117from ..schema import PropertyListing118119SITE = "https://www.vendre.ca"120SITEMAPS = [f"{SITE}/res.xml", f"{SITE}/mpx.xml", f"{SITE}/com.xml", f"{SITE}/lnd.xml"]121DETAIL_LIMIT = int(os.environ.get("IMMOKA_VENDRE_DETAIL_LIMIT", "400"))122AGENCY = "Vendre.ca"123124_LOC_RE = re.compile(r"<loc>([^<]+)</loc>")125# /fr/<type>-a-vendre-<ville>/<adresse>-<vid>/  (le type peut contenir des tirets)126_URL_RE = re.compile(127    r"https://www\.vendre\.ca/fr/([a-z0-9-]+?)-a-vendre-([a-z0-9-]+)/"128    r"([a-z0-9-]+?)-([a-z0-9]+)/?$", re.I)129_PHOTO_RE = re.compile(r"https://cloud\.vendre\.ca/[^\"'\\ ]+?_lrg\.(?:webp|jpg)", re.I)130131# slugs d'URL -> vocabulaire brut (finalize() normalise)132_TYPES = {133    "maisons": "Maison", "maisons-neuves": "Maison", "chalets": "Chalet",134    "condos": "Condo", "condos-neufs": "Condo", "lofts": "Loft",135    "fermettes": "Fermette", "duplex": "Duplex", "triplex": "Triplex",136    "4plex": "Quadruplex", "5plex": "Quintuplex", "multiplex": "Multiplex",137    "propriete-commerciale": "Commercial", "condo-commercial": "Commercial",138    "edifice-bureaux": "Commercial", "batiment-industriel": "Commercial",139    "ferme": "Fermette/Agricole", "terrain": "Terrain",140}141142143class VendreCaConnector(BaseConnector):144    source_id = "vendre_ag_ca"145    request_delay = 0.4146147    def fetch(self) -> list[PropertyListing]:148        by_id: dict[str, PropertyListing] = {}149        for sm in SITEMAPS:150            # depuis 2026-09 le serveur renvoie HTTP 404 sur les sitemaps tout151            # en servant le XML complet — on garde le corps s'il est un urlset152            try:153                xml = self.get(sm).text154            except requests.HTTPError as e:155                xml = e.response.text if e.response is not None else ""156            except Exception:157                continue158            if "<urlset" not in xml:159                continue160            for url in _LOC_RE.findall(xml):161                lst = self._to_listing(url)162                if lst and lst.external_id not in by_id:163                    by_id[lst.external_id] = lst164        listings = list(by_id.values())165        du.enrich(self, listings, DETAIL_LIMIT, parse_vendre_detail, key="v1")166        # n° MLS connu -> external_id (clé de dédup Centris contre les bannières) ;167        # les fiches sans MLS (vendeurs privés) gardent le VID, jamais masquées.168        out: dict[str, PropertyListing] = {}169        for lst in listings:170            mls = str(lst.details.pop("_mls", "") or "")171            if mls:172                lst.mls = mls173                lst.external_id = mls174            region = lst.details.pop("_region", "")175            if region and not lst.region:176                lst.region = region177            # la fiche détail bat les valeurs dérivées du slug d'URL178            addr = lst.details.pop("_addr", "")179            if addr:180                lst.address = addr181                lst.title = addr182            city = lst.details.pop("_city", "")183            if city:184                lst.city = city185            out.setdefault(lst.external_id, lst)186        return list(out.values())187188    def _to_listing(self, url: str) -> PropertyListing | None:189        m = _URL_RE.match(url.strip())190        if not m:191            return None192        type_s, city_s, addr_s, vid = m.groups()193        # le n° civique ouvre le VID (« 160bq » -> 160 Chemin Le Nordais)194        mc = re.match(r"(\d+)", vid)195        addr = ((mc.group(1) + " ") if mc else "") + _deslug(addr_s)196        return PropertyListing(197            source=self.source_id, external_id=vid, url=url,198            title=addr,199            address=addr,200            city=_deslug(city_s),201            property_type=normalize_property_type(_TYPES.get(type_s, type_s)),202            agency=AGENCY,203        )204205206# ---------------------------------------------------------------------------207def parse_vendre_detail(html: str) -> dict:208    """JSON-LD Place (adresse/géo) + RealEstateListing (MLS, année, description)209    + Offer (prix, courtier) ; galerie cloud.vendre.ca pleine résolution."""210    out: dict = {}211    details: dict = {}212    for node in du.ld_nodes(html):213        t = node.get("@type")214        if t == "Place":215            addr = node.get("address") or {}216            if addr.get("streetAddress"):217                details["_addr"] = str(addr["streetAddress"])218            if addr.get("addressLocality"):219                details["_city"] = str(addr["addressLocality"])220            if addr.get("postalCode"):221                details["postal_code"] = str(addr["postalCode"])222            geo = node.get("geo") or {}223            try:224                out["lat"], out["lng"] = float(geo["latitude"]), float(geo["longitude"])225            except (KeyError, TypeError, ValueError):226                pass227        elif t == "RealEstateListing":228            if node.get("description"):229                out["description"] = _html.unescape(str(node["description"])).strip()[:4000]230            ident = node.get("identifier") or {}231            if isinstance(ident, dict) and ident.get("value"):232                details["_mls"] = str(ident["value"])233            y = node.get("yearBuilt")234            if y and str(y).isdigit():235                out["year_built"] = int(y)236            geo = node.get("geo") or {}237            if "lat" not in out:238                try:239                    out["lat"], out["lng"] = float(geo["latitude"]), float(geo["longitude"])240                except (KeyError, TypeError, ValueError):241                    pass242        elif t == "Offer":243            p = node.get("price")244            try:245                out["price"] = float(p)246                out["price_label"] = f"{float(p):,.0f} $".replace(",", " ")247            except (TypeError, ValueError):248                pass249            seller = node.get("seller") or {}250            if isinstance(seller, dict) and seller.get("name"):251                out["broker_name"] = str(seller["name"])252        elif t == "BreadcrumbList":253            for it in node.get("itemListElement") or []:254                name = (it or {}).get("name", "")255                mr = re.match(r"Région de\s+(.+)", str(name))256                if mr:257                    details["_region"] = mr.group(1).strip()258259    # galerie pleine résolution (ordre du HTML, dédoublonnée)260    seen, imgs = set(), []261    for u in _PHOTO_RE.findall(html):262        if u not in seen:263            seen.add(u)264            imgs.append(u)265    if imgs:266        out["images"] = imgs267268    # chambres / salles de bains (l'entête de la fiche, ex. « 5 chambres à269    # coucher, 2 bains ») — finalize() fait le reste depuis la description.270    text = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", html)))271    mb = re.search(r"(\d{1,2})\s*chambres?\s*à\s*coucher", text, re.I)272    if mb:273        out["bedrooms"] = int(mb.group(1))274    ms = re.search(r"(\d{1,2})\s*bains?\b", text, re.I)275    if ms:276        out["bathrooms"] = int(ms.group(1))277278    if details:279        out["details"] = details280    return out281282283def _deslug(s: str) -> str:284    return re.sub(r"\s+", " ", s.replace("-", " ")).strip().title()285
Files main
Menu

Theme