SPB Git

Repository Public

expert_immobilier_pm.py 9.6 KB 235 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/expert_immobilier_pm.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/expert_immobilier_pm.py : L'Expert Immobilier P.M. (Laval, QC)91#   Vrai site : expertimmobilierpm.com (WordPress + plugin mw-properties2, la92#   même plateforme marketingwebsites.ca que KW Urbain). NB : l'ancienne URL du93#   registre (lexpertimmobilier.com) était une agence de Casablanca — corrigée.94#   La page /proprietes/ rend les fiches côté serveur (n° Centris dans l'URL) ;95#   la fiche détail fournit la galerie complète (marketingwebsites) + description.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import html as _html100import os101import re102from urllib.parse import unquote_plus103104from .base import BaseConnector105from . import _detailutil as du106from ..normalize import parse_price107from ..schema import PropertyListing108109BASE = "https://expertimmobilierpm.com"110LISTINGS = f"{BASE}/proprietes/"111DETAIL_LIMIT = int(os.environ.get("IMMOKA_EPM_DETAIL_LIMIT", "300"))112113# lien fiche : /properties/{Adresse+Avec+Plus}/{no-centris}114_LINK_RE = re.compile(r'/properties/([^"/]+)/(\d{6,})')115_IMG_RE = re.compile(116    r'https://realestate\.marketingwebsites\.ca/property-images/\d+/[^"\'\\ ]+\.(?:jpg|jpeg|png|webp)',117    re.I)118_META_DESC_RE = re.compile(r'<meta\s+name="description"\s+content="([^"]{40,})"', re.I)119120_TYPE_MAP = {121    "plain-pied": "Maison", "à étages": "Maison", "a etages": "Maison",122    "à paliers": "Maison", "mobile": "Maison mobile", "cottage": "Maison",123    "appartement": "Condo", "condo": "Condo", "copropriété": "Condo", "loft": "Condo",124    "duplex": "Duplex", "triplex": "Triplex", "quadruplex": "Multiplex",125    "quintuplex": "Multiplex", "plex": "Multiplex", "revenus": "Multiplex",126    "terrain": "Terrain", "fermette": "Fermette/Agricole", "ferme": "Fermette/Agricole",127    "chalet": "Chalet", "commercial": "Commercial", "commerciale": "Commercial",128}129130131def _norm_type(txt: str) -> str:132    k = txt.lower()133    for key, canon in _TYPE_MAP.items():134        if key in k:135            return canon136    return ""137138139class ExpertImmobilierPmConnector(BaseConnector):140    source_id = "expert_immobilier_pm"141    request_delay = 0.6142143    def fetch(self) -> list[PropertyListing]:144        try:145            html = self.get(LISTINGS).text146        except Exception:147            return []148        # premières positions de chaque n° Centris (les liens titre+image se149        # répètent : on garde la 1re occurrence de chaque fiche, dans l'ordre)150        firsts: list[tuple[str, str, int]] = []   # (addr_slug, centris, index)151        seen: set[str] = set()152        for m in _LINK_RE.finditer(html):153            c = m.group(2)154            if c not in seen:155                seen.add(c)156                firsts.append((m.group(1), c, m.start()))157        by_id: dict[str, PropertyListing] = {}158        for i, (addr_slug, centris, idx) in enumerate(firsts):159            end = firsts[i + 1][2] if i + 1 < len(firsts) else len(html)160            by_id[centris] = self._to_listing(addr_slug, centris, html[idx:end])161        listings = list(by_id.values())162        du.enrich(self, listings, DETAIL_LIMIT, parse_epm_detail, key="v2")163        return listings164165    def _to_listing(self, addr_slug: str, centris: str, block: str) -> PropertyListing:166        address = unquote_plus(addr_slug).strip()167        flat = _html.unescape(re.sub(r"<[^>]+>", " | ", block))168        flat = re.sub(r"\s*\|\s*", " | ", flat)169        flat = re.sub(r"[ \t]+", " ", flat)170        # tout est dans la carte : type | # centris | adresse | ville | N Chambres171        #   | N Bains | S MC Habitable | $prix172        mt = re.search(r"([A-Za-zÀ-ÿ'’ -]{4,40})\s*(?:\|\s*)+#\s*" + centris, flat)173        ptype = _norm_type(mt.group(1)) if mt else ""174        city = ""175        mc = re.search(re.escape(address) + r"\s*(?:\|\s*)+([A-Za-zÀ-ÿ'()/. -]{3,45}?)\s*\|",176                       flat)177        if mc:178            city = mc.group(1).strip(" |")179        beds = re.search(r"\|\s*(\d{1,2})\s*\|\s*Chambres?", flat)180        baths = re.search(r"\|\s*(\d{1,2})\s*\|\s*Bains?", flat)181        area = re.search(r"([\d.,]+)\s*MC\s*\|\s*Habitable", flat, re.I)182        area_sqft = None183        if area:184            try:185                area_sqft = round(float(area.group(1).replace(",", ".")) * 10.7639)186            except ValueError:187                pass188        mprice = re.search(r"\$\s*([\d  ,]{4,})", flat)189        price = parse_price(mprice.group(0)) if mprice else None190        thumb = _IMG_RE.search(block)191        return PropertyListing(192            source=self.source_id,193            external_id=centris,194            url=f"{BASE}/properties/{addr_slug}/{centris}",195            title=address,196            address=address,197            city=city,198            region="",199            property_type=ptype,200            price=price,201            price_label=(mprice.group(0).strip() if mprice else ""),202            bedrooms=int(beds.group(1)) if beds else None,203            bathrooms=int(baths.group(1)) if baths else None,204            area_sqft=area_sqft,205            mls=centris,206            images=[thumb.group(0)] if thumb else [],207            broker_name="L'Expert Immobilier P.M.",208        )209210211def parse_epm_detail(html: str) -> dict:212    """Fiche détail : galerie complète (marketingwebsites), description, ch/sdb, prix."""213    out: dict = {}214    seen, imgs = set(), []215    for u in _IMG_RE.findall(html):216        base = re.sub(r"/thumbs-\d+/", "/", u)   # préférer la pleine résolution217        if base not in seen:218            seen.add(base)219            imgs.append(base)220    if imgs:221        out["images"] = imgs222    md = _META_DESC_RE.search(html)223    if md:224        out["description"] = _html.unescape(md.group(1)).strip()225    # prix : uniquement un montant plausible suivi de $ (chambres/sdb viennent226    # de la carte, plus fiables que le texte aplati de la fiche)227    t = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", html)))228    for m in re.finditer(r"([\d][\d  ]{4,})\s*\$", t):229        p = parse_price(m.group(0))230        if p and p >= 20000:231            out["price"] = p232            out["price_label"] = m.group(0).strip()233            break234    return out235
Files main
Menu

Theme