SPB Git

Repository Public

duquesimms.py 10.9 KB 274 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/duquesimms.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-2313# Last Modified    : 2026-09-1314#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/duquesimms.py : Duque Simms (duquesimms.com) — agence indépendante91#   de Montréal (NDG, Côte-des-Neiges, Ouest-de-l'Île), ~25 inscriptions.92#93#   Site WordPress/Elementor (plateforme proprius/e-mmobilier, photos sur94#   cdn.proprius.e-mmobilier.ca). Découverte par property-sitemap.xml : URLs95#   fr /property/{n° Centris}/ (les /en/ sont des doublons de langue).96#97#   TOUT vient de la fiche détail (du.enrich) : JSON-LD RealEstateListing98#   (description, contentLocation adresse complète + GPS, offers[].price avec99#   businessFunction Sell, keywords = type, seller = courtier nom/téléphone)100#   + blocs HTML property-characteristic (libellé/valeurs), property-expense101#   (taxes, énergie), property-evaluation, compteurs chambres/salles de bain102#   (icônes bedroom.svg/bathroom.svg suivies du nombre), galerie swiper103#   cdn …-pi.jpg (les -c.jpg sont des portraits). Les locations (prix de104#   loyer) sont écartées par le seuil de prix vente.105#106#   Agence première main (pas d'infixe _ag_) : ses fiches battent les copies107#   portails au même n° Centris dans la dédup.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import html as _html112import os113import re114115from .base import BaseConnector116from . import _detailutil as du117from ..schema import PropertyListing118119SITE = "https://duquesimms.com"120SITEMAP = SITE + "/property-sitemap.xml"121AGENCY = "Duque Simms"122DETAIL_LIMIT = int(os.environ.get("IMMOKA_DUQUESIMMS_DETAIL_LIMIT", "80"))123MIN_SALE_PRICE = 20000     # sous ce prix : loyer mensuel (location) → écarté124125_LOC_RE = re.compile(r"<loc>\s*(https://duquesimms\.com/property/(\d{6,10})/?)\s*</loc>")126_ADDR_RE = re.compile(r"^(.*?),\s*(.+?)\s*([A-Z]\d[A-Z]\s?\d[A-Z]\d)?$")127_CHAR_RE = re.compile(r'property-characteristic-type">(.*?)</span>(.*?)</div>', re.S)128_SUBVAL_RE = re.compile(r'property-subcharacteristic-value">(.*?)</span>', re.S)129_EXP_RE = re.compile(r'property-expense-label">(.*?)</span>.*?property-money-amount">'130                     r'([\d\s ,]+)</span>', re.S)131_EVAL_RE = re.compile(r'property-evaluation-label">(.*?)</span>.*?property-money-amount">'132                      r'([\d\s ,]+)</span>', re.S)133_BEDS_RE = re.compile(r'bedroom\.svg.{0,900}?elementor-widget-container">\s*(\d+)\s*<', re.S)134_BATHS_RE = re.compile(r'bathroom\.svg.{0,900}?elementor-widget-container">\s*(\d+)\s*<', re.S)135_IMG_RE = re.compile(r'https://cdn\.proprius\.e-mmobilier\.ca/([A-Z0-9]+-pi)\.jpe?g', re.I)136137138class DuqueSimmsConnector(BaseConnector):139    source_id = "duquesimms"140    request_delay = 0.4141142    def fetch(self) -> list[PropertyListing]:143        # SiteGround sert un challenge sgcaptcha en HTTP 202 (sans exception) :144        # get_resilient escalade (Oxylabs → Scrapfly ASP → Bright Data)145        xml = self.get_resilient(SITEMAP).text146        by_id: dict[str, PropertyListing] = {}147        for url, mls in _LOC_RE.findall(xml):148            by_id.setdefault(mls, PropertyListing(149                source=self.source_id, external_id=mls,150                url=url if url.endswith("/") else url + "/",151                title="", mls=mls, agency=AGENCY, broker_name=AGENCY,152            ))153        listings = list(by_id.values())154        du.enrich(self, listings, DETAIL_LIMIT, _parse_detail, key="v1",155                  fetch_html=lambda u: self.get_resilient(u).text)156        out = []157        for lst in listings:158            if not lst.price or lst.price < MIN_SALE_PRICE:159                continue               # location (loyer) ou fiche vide160            if not lst.title:161                lst.title = f"{lst.property_type or 'Propriété'} à vendre — " \162                            f"{lst.address or lst.city}".strip(" —")163            if lst.price and not lst.price_label:164                lst.price_label = f"{int(lst.price):,} $".replace(",", " ")165            out.append(lst)166        return out167168169def _txt(s: str) -> str:170    return re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", s))).strip()171172173def _parse_detail(html: str) -> dict:174    node = None175    for n in du.ld_nodes(html):176        if n.get("@type") == "RealEstateListing":177            node = n178            break179    if node is None:180        return {}181    out: dict = {}182    details: dict = {}183    features: list[str] = []184185    desc = _html.unescape(str(node.get("description") or "")).strip()186    if desc:187        out["description"] = desc188189    kw = node.get("keywords") or []190    if isinstance(kw, str):191        kw = [kw]192    if kw:193        out["property_type"] = str(kw[0]).strip()194        details["Type de propriété"] = out["property_type"]195        if len(kw) > 1:196            details["Catégorie"] = str(kw[1]).strip()197198    loc = node.get("contentLocation") or {}199    if isinstance(loc, dict):200        full = _html.unescape(str(loc.get("address") or "")).strip()201        m = _ADDR_RE.match(full)202        if m:203            out["address"] = m.group(1).strip()204            out["city"] = m.group(2).strip()205            if m.group(3):206                details["Code postal"] = m.group(3)207        elif full:208            out["address"] = full209        try:210            out["lat"], out["lng"] = float(loc["latitude"]), float(loc["longitude"])211        except (KeyError, TypeError, ValueError):212            pass213214    offers = node.get("offers") or []215    if isinstance(offers, dict):216        offers = [offers]217    sellers: list[str] = []218    for off in offers:219        if not isinstance(off, dict):220            continue221        if "Sell" not in str(off.get("businessFunction") or "Sell"):222            continue223        if out.get("price") is None and off.get("price"):224            try:225                out["price"] = float(str(off["price"]).replace(" ", ""))226            except ValueError:227                pass228        seller = off.get("seller") or {}229        if isinstance(seller, dict) and seller.get("name"):230            name = str(seller["name"]).strip()231            if name not in sellers:232                sellers.append(name)233            if "broker_phone" not in out:234                tel = str(seller.get("telephone") or "").strip()235                if re.fullmatch(r"\d{10}", tel):236                    out["broker_phone"] = f"{tel[:3]} {tel[3:6]}-{tel[6:]}"237    if sellers:238        out["broker_name"] = " et ".join(sellers[:2])239240    bm, tm = _BEDS_RE.search(html), _BATHS_RE.search(html)241    if bm:242        out["bedrooms"] = int(bm.group(1))243    if tm:244        out["bathrooms"] = int(tm.group(1))245246    for label, blob in _CHAR_RE.findall(html):247        label = _txt(label)248        vals = [_txt(v) for v in _SUBVAL_RE.findall(blob)]249        vals = [v for v in vals if v]250        if label and vals:251            details[label] = ", ".join(vals)252            features.append(f"{label} : {details[label]}"253                            if len(details[label]) < 40 else label)254255    for rx in (_EXP_RE, _EVAL_RE):256        for label, amount in rx.findall(html):257            label, amount = _txt(label), _txt(amount).replace(" ", " ")258            if label and amount:259                details[label] = f"{amount} $"260261    imgs, seen = [], set()262    for base in _IMG_RE.findall(html):263        if base not in seen:264            seen.add(base)265            imgs.append(f"https://cdn.proprius.e-mmobilier.ca/{base}.jpg")266    if imgs:267        out["images"] = imgs268269    if details:270        out["details"] = details271    if features:272        out["features"] = features273    return out274
Files main
Menu

Theme