SPB Git

Repository Public

duproprio.py 13.3 KB 330 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/duproprio.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1814#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/duproprio.py : DuProprio (FSBO — vente sans courtier)91#92#   DuProprio est la grande plateforme québécoise de vente « à vendre par le93#   propriétaire » (sans agence). Segment complémentaire absent de toutes les94#   bannières de courtage. Énumération EXHAUSTIVE via les sitemaps FR par région95#   du Québec (`/sitemaps/fr/<region>-listings.xml.gz`) : l'URL encode déjà96#   région, ville, type et l'id DuProprio (= external_id). La fiche détail97#   (JSON-LD Product) fournit prix, description et galerie ; enrichissement98#   plafonné + cache (comme les autres connecteurs). Scrapfly en secours si le99#   fetch direct est bloqué.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import gzip104import io105import os106import re107108from .base import BaseConnector109from . import _detailutil as du110from ..normalize import normalize_property_type, parse_price111from ..schema import PropertyListing112113SITEMAP_INDEX = "https://duproprio.com/sitemaps/fr/index.xml.gz"114DETAIL_LIMIT = int(os.environ.get("IMMOKA_DUPROPRIO_DETAIL_LIMIT", "500"))115AGENCY = "DuProprio (sans courtier)"116117_LOC_RE = re.compile(r"<loc>([^<]+)</loc>")118# /fr/<region>/<ville>/<type>-a-vendre/<slug>-<id>119_URL_RE = re.compile(120    r"https://duproprio\.com/fr/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+?)-a-vendre/([a-z0-9-]+?)-(\d{5,})/?$",121    re.I)122_PHOTO_RE = re.compile(123    r"https://photos\.duproprio\.com/photos/public/for_sale/\d+/\d+/[^\"'\\ ]+?\.jpg", re.I)124_LDPROD_RE = re.compile(r'<script[^>]+application/ld\+json[^>]*>(.*?)</script>', re.S | re.I)125126127class DuProprioConnector(BaseConnector):128    source_id = "duproprio"129    request_delay = 0.4130131    def fetch(self) -> list[PropertyListing]:132        by_id: dict[str, PropertyListing] = {}133        for sm in self._region_listing_sitemaps():134            for url in self._sitemap_locs(sm):135                lst = self._to_listing(url)136                if lst and lst.external_id not in by_id:137                    by_id[lst.external_id] = lst138        listings = list(by_id.values())139        du.enrich(self, listings, DETAIL_LIMIT, _parse_dp_detail,140                  key="v2", fetch_html=self._fetch_detail)141        return listings142143    # -- sitemaps --------------------------------------------------------------144    def _region_listing_sitemaps(self) -> list[str]:145        xml = self._get_gz(SITEMAP_INDEX)146        # uniquement les sitemaps d'INSCRIPTIONS par région (Québec)147        return [u for u in _LOC_RE.findall(xml) if u.endswith("-listings.xml.gz")]148149    def _sitemap_locs(self, url: str) -> list[str]:150        return [u for u in _LOC_RE.findall(self._get_gz(url)) if "/fr/" in u]151152    def _get_gz(self, url: str) -> str:153        try:154            raw = self.get(url).content155        except Exception:156            return ""157        try:158            return gzip.GzipFile(fileobj=io.BytesIO(raw)).read().decode("utf-8", "ignore")159        except OSError:160            return raw.decode("utf-8", "ignore")   # déjà décompressé161162    # -- mapping ---------------------------------------------------------------163    def _to_listing(self, url: str) -> PropertyListing | None:164        m = _URL_RE.match(url.strip())165        if not m:166            return None167        region_s, city_s, type_s, addr_s, did = m.groups()168        return PropertyListing(169            source=self.source_id, external_id=did, url=url,170            title=_deslug(addr_s),171            address=_deslug(re.sub(r"^(hab|com|ter|multi|imm)-", "", addr_s)),172            city=_deslug(city_s),173            region=_region(region_s),174            property_type=normalize_property_type(type_s.replace("-", " ")),175            agency=AGENCY, broker_name="",176        )177178    def _fetch_detail(self, url: str) -> str:179        html = ""180        try:181            html = self.get(url).text182        except Exception:183            html = ""184        if "application/ld+json" not in html:      # bloqué -> Scrapfly (ASP)185            try:186                html = self.get_scrapfly(url, render_js=False, asp=True)187            except Exception:188                pass189        return html190191192# ---------------------------------------------------------------------------193def _parse_dp_detail(html: str) -> dict:194    import json, html as _h195    out: dict = {}196    for block in _LDPROD_RE.findall(html):197        try:198            d = json.loads(block)199        except ValueError:200            continue201        if isinstance(d, dict) and d.get("@type") == "Product":202            off = d.get("offers") or {}203            p = parse_price(str(off.get("price") or "")) if off.get("price") else None204            if p:205                out["price"] = p206                out["price_label"] = f"{p:,.0f} $".replace(",", " ")207            if d.get("description"):208                out["description"] = _h.unescape(str(d["description"])).strip()[:4000]209            break210    # coordonnées GPS du JSON-LD Residence (geo) — géocodage gratuit211    for block in _LDPROD_RE.findall(html):212        try:213            d = json.loads(block)214        except ValueError:215            continue216        geo = d.get("geo") if isinstance(d, dict) else None217        if isinstance(geo, dict):218            try:219                lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))220            except (TypeError, ValueError):221                continue222            if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:223                out["lat"], out["lng"] = lat, lng224            break225    # galerie COMPLÈTE : le JSON « "photos":[{...}] » de la page liste toutes les226    # photos (le JSON-LD/HTML n'en montre qu'une). On prend la plus haute résolution.227    imgs, seen = [], set()228    mgal = re.search(r'"photos"\s*:\s*(\[\{.*?\}\])', html, re.S)229    if mgal:230        try:231            for ph in json.loads(mgal.group(1)):232                fmt = ph.get("formats") or {}233                rel = fmt.get("1600") or fmt.get("1024") or fmt.get("600")234                if rel:235                    u = rel if rel.startswith("http") else f"https://photos.duproprio.com/{rel.lstrip('/')}"236                    if u not in seen:237                        seen.add(u); imgs.append(u)238        except ValueError:239            pass240    if not imgs:                       # repli : URLs photos dans le HTML brut241        for u in _PHOTO_RE.findall(html):242            if u not in seen:243                seen.add(u); imgs.append(u)244    if imgs:245        out["images"] = imgs246    text = re.sub(r"\s+", " ", _h_unescape(html))247    mb = re.search(r"(\d+)\s*chambre", text, re.I)248    if mb:249        out["bedrooms"] = int(mb.group(1))250    ms = re.search(r"(\d+)\s*salle[s]?\s*de\s*bain", text, re.I)251    if ms:252        out["bathrooms"] = int(ms.group(1))253254    details: dict = {}255    features: list[str] = []256257    # --- Dimensions des pièces (tableau des pièces) --------------------------258    rooms = []259    for blk in re.split(r'listing-rooms-details__table__item-container',260                        html)[1:41]:261        blk = blk.split("item-container")[0]262        def cell(marker):263            m = re.search(marker + r'[^>]*>(.*?)</div>', blk, re.S)264            return re.sub(r"\s+", " ", _h_unescape(m.group(1))).strip() if m else ""265        nom = cell(r'item--room"')266        niveau = cell(r'item--storey"').replace("Étage :", "").strip()267        dim = cell(r'item--dimensions"').replace("Dimensions :", "").strip()268        rev = cell(r'item--flooring"').replace("Plancher :", "").strip()269        if nom:270            rooms.append({"nom": nom, "niveau": niveau,271                          "dimensions": dim, "revetement": rev})272    if rooms:273        details["pieces"] = rooms[:30]274275    # --- Caractéristiques de la propriété (rangées pointillées) ---------------276    for lm, vm in re.findall(277            r'listing-box__dotted-row">\s*<div>(.*?)</div>\s*<div>\s*</div>\s*'278            r'<div>(.*?)</div>', html, re.S):279        label = re.sub(r"\s+", " ", _h_unescape(lm)).strip()280        value = re.sub(r"\s+", " ", _h_unescape(vm)).strip()281        if not label or not value or label == "Prix demandé":282            continue283        if label == "Année de construction":284            my = re.search(r"(19|20)\d{2}", value)285            if my:286                out["year_built"] = int(my.group(0))287        elif label in ("Superficie du terrain", "Superficie habitable",288                       "Aire habitable", "Superficie du bâtiment"):289            mp = re.search(r"([\d\s,.]+)\s*pi", value)290            if mp:291                try:292                    sqft = float(mp.group(1).replace(" ", "").replace(",", ""))293                    out["lot_sqft" if "terrain" in label else "area_sqft"] = sqft294                except ValueError:295                    pass296        features.append(f"{label} : {value}")297        details[label] = value298299    # --- Remarques du proprio (texte long, souvent plus riche que le JSON-LD) --300    mrq = re.search(r'listing-owners-comments__description[^>]*>(.*?)</div>',301                    html, re.S)302    if mrq:303        remarques = re.sub(r"\s+", " ", _h_unescape(mrq.group(1))).strip()304        if remarques:305            details["remarques_proprio"] = remarques[:6000]306            if len(remarques) > len(out.get("description") or ""):307                out["description"] = remarques[:6000]308309    if features:310        out["features"] = features311    if details:312        out["details"] = details313    return out314315316def _h_unescape(html: str) -> str:317    import html as _h318    return _h.unescape(re.sub(r"<[^>]+>", " ", html))319320321def _deslug(s: str) -> str:322    return re.sub(r"\s+", " ", s.replace("-", " ").replace("_", " ")).strip().title()323324325def _region(slug: str) -> str:326    r = _deslug(slug)327    return (r.replace("Quebec", "Québec").replace("Montreal", "Montréal")328             .replace("Monteregie", "Montérégie").replace("Laurentides", "Laurentides")329             .replace("Mauricie", "Mauricie").replace("Estrie", "Estrie"))330
Files main
Menu

Theme