SPB Git

Repository Public

engel_volkers.py 9.5 KB 246 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/engel_volkers.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1214#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/engel_volkers.py : Engel & Völkers Montréal / Québec (luxe)91#   Le site local immobilier.evquebec.com publie un property-sitemap.xml92#   exhaustif (~1240 fiches, /propriete/{no-centris}/). Chaque fiche a un93#   JSON-LD RealEstateListing (prix, adresse, description, n° Centris). La94#   galerie est servie séquentiellement sur media.evquebec.com/listings/{id}/NN.webp.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import html as _html99import os100import re101102from .base import BaseConnector103from . import _detailutil as du104from ..schema import PropertyListing105106SITEMAP = "https://immobilier.evquebec.com/property-sitemap.xml"107MEDIA = "https://media.evquebec.com/listings"108DETAIL_LIMIT = int(os.environ.get("IMMOKA_EV_DETAIL_LIMIT", "400"))109GALLERY_MAX = 60110111_PROP_RE = re.compile(r'https://immobilier\.evquebec\.com/propriete/(\d{5,})/')112_NAME_RE = re.compile(r'^(.*?)\s+à vendre\b\s*-?\s*(.*)$', re.I)113114115class EngelVolkersConnector(BaseConnector):116    source_id = "engel_volkers"117    request_delay = 0.4118    use_detail_cache = True119120    def fetch(self) -> list[PropertyListing]:121        try:122            xml = self.get(SITEMAP).text123        except Exception:124            return []125        ids, seen = [], set()126        for m in _PROP_RE.finditer(xml):     # ne garder que les URLs FR127            if m.group(1) not in seen:128                seen.add(m.group(1))129                ids.append(m.group(1))130        listings = [PropertyListing(source=self.source_id, external_id=cid,131                                    url=f"https://immobilier.evquebec.com/propriete/{cid}/",132                                    mls=cid, broker_name="Engel & Völkers Québec")133                    for cid in ids]134        self._enrich(listings)135        return listings136137    def _enrich(self, listings: list[PropertyListing]) -> None:138        from .. import db139        con = db.connect()140        budget = DETAIL_LIMIT141        try:142            for lst in listings:143                d = db.get_cached_detail(con, self.source_id, lst.external_id, "v1")144                if d is None:145                    if budget <= 0:146                        continue147                    try:148                        d = self._parse(self.get(lst.url).text, lst.external_id)149                    except Exception:150                        d = {}151                    db.put_cached_detail(con, self.source_id, lst.external_id, "v1", d)152                    budget -= 1153                _apply(lst, d)154        finally:155            con.close()156157    def _parse(self, html: str, centris: str) -> dict:158        out: dict = {}159        for n in du.ld_nodes(html):160            t = n.get("@type")161            types = t if isinstance(t, list) else [t]162            if "RealEstateListing" in types:163                if n.get("description"):164                    out["description"] = _html.unescape(str(n["description"])).strip()165                offer = n.get("offers") or {}166                try:167                    p = float(offer.get("price"))168                    if p >= 10_000:169                        out["price"] = p170                except (TypeError, ValueError):171                    pass172                name = _html.unescape(n.get("name", "")).strip()173                if name:174                    out.update(_parse_name(name))175                break176        # bedrooms / bathrooms depuis le texte177        text = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", html)))178        mb = re.search(r"(\d+)\s*chambre", text, re.I)179        if mb:180            out["bedrooms"] = int(mb.group(1))181        ms = re.search(r"(\d+)\s*salle[s]?\s*de\s*bain", text, re.I)182        if ms:183            out["bathrooms"] = int(ms.group(1))184        out["images"] = self._gallery(centris)185        return out186187    def _gallery(self, centris: str) -> list[str]:188        """Galerie séquentielle NN.webp — on s'arrête au premier trou (HEAD rapide)."""189        urls = []190        for i in range(1, GALLERY_MAX + 1):191            u = f"{MEDIA}/{centris}/{i:02d}.webp"192            try:193                r = self.session.head(u, timeout=8)194            except Exception:195                break196            if r.status_code != 200:197                break198            urls.append(u)199        return urls200201202def _parse_name(name: str) -> dict:203    """« Condo à vendre - Centre-ville - 1288 Av. …, Montréal (Ville-Marie), Montréal »."""204    out: dict = {}205    m = _NAME_RE.search(name)206    if not m:207        return out208    out["property_type"] = m.group(1).strip()209    rest = m.group(2).strip()210    segs = [s.strip() for s in rest.split(" - ") if s.strip()]211    loc = segs[-1] if segs else rest212    # municipalité = segment contenant « ( » ; adresse = ce qui précède213    commas = [c.strip() for c in loc.split(",")]214    muni_idx = next((i for i, c in enumerate(commas) if "(" in c), None)215    if muni_idx is not None:216        muni = commas[muni_idx]217        ps = re.search(r"\(([^)]+)\)", muni)218        out["city"] = re.sub(r"\s*\([^)]*\)", "", muni).strip()219        if ps:220            out["sector"] = ps.group(1).strip()221        addr = ", ".join(commas[:muni_idx]).strip()222        if addr:223            out["address"] = addr224    elif len(commas) >= 2:225        # pas d'arrondissement : dernier segment = municipalité, le reste = adresse226        out["city"] = commas[-1]227        out["address"] = ", ".join(commas[:-1]).strip()228    else:229        out["address"] = loc230    if len(segs) > 1 and not out.get("sector"):231        out["sector"] = segs[0]232    return out233234235def _apply(lst: PropertyListing, d: dict) -> None:236    if not d:237        return238    for f in ("address", "city", "sector", "property_type", "description"):239        if d.get(f) and not getattr(lst, f, ""):240            setattr(lst, f, d[f])241    for f in ("price", "bedrooms", "bathrooms"):242        if d.get(f) is not None and getattr(lst, f, None) in (None, 0):243            setattr(lst, f, d[f])244    if d.get("images") and len(d["images"]) > len(lst.images):245        lst.images = d["images"]246
Files main
Menu

Theme