SPB Git

Repository Public

profusion.py 10.2 KB 255 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/profusion.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/profusion.py : Profusion Immobilier (luxe, affilié Forbes/Christie's)91#   Énumération : la page « nos-inscriptions » liste toutes les fiches en HTML92#   rendu serveur, sous forme /propriete/{no-centris}/. Chaque fiche publie un93#   JSON-LD RealEstateListing (adresse, description, prix, courtier) + un bloc94#   de specs « Libellé: valeur » + une galerie profusionimmo.ca.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import html as _html99import json100import os101import re102103from .base import BaseConnector104from . import _detailutil as du105from ..schema import PropertyListing106107SITE = "https://www.profusion.global"108LISTING_PAGE = f"{SITE}/acheter/nos-inscriptions/"109DETAIL_LIMIT = int(os.environ.get("IMMOKA_PROFUSION_DETAIL_LIMIT", "500"))110111_PROP_RE = re.compile(r'/propriete/(\d{5,})/')112_IMG_RE = re.compile(r'https://profusionimmo\.ca/public/user_files/proprietes/fiche/\d+-\d+\.jpg', re.I)113# nom JSON-LD : « {Type} à vendre à {Ville (Secteur)} – {Adresse civique} »114_NAME_RE = re.compile(r'^(.*?)\s+à vendre à\s+(.+?)\s*$', re.I)115_SPEC_RE = re.compile(r'([A-Za-zÀ-ÿ\'’()/ ]{3,40})\s*:\s*([^<|]{1,60})')116117118class ProfusionConnector(BaseConnector):119    source_id = "profusion"120    request_delay = 0.5121    use_detail_cache = True122123    def fetch(self) -> list[PropertyListing]:124        try:125            html = self.get(LISTING_PAGE).text126        except Exception:127            return []128        ids: list[str] = []129        seen = set()130        for m in _PROP_RE.finditer(html):131            if m.group(1) not in seen:132                seen.add(m.group(1))133                ids.append(m.group(1))134        listings = [PropertyListing(source=self.source_id, external_id=cid,135                                    url=f"{SITE}/propriete/{cid}/", mls=cid,136                                    broker_name="Profusion Immobilier")137                    for cid in ids]138        self._enrich(listings)139        return listings140141    def _enrich(self, listings: list[PropertyListing]) -> None:142        from .. import db143        con = db.connect()144        budget = DETAIL_LIMIT145        try:146            for lst in listings:147                d = db.get_cached_detail(con, self.source_id, lst.external_id, "v1")148                if d is None:149                    if budget <= 0:150                        continue151                    try:152                        d = parse_profusion_detail(self.get(lst.url).text)153                    except Exception:154                        d = {}155                    db.put_cached_detail(con, self.source_id, lst.external_id, "v1", d)156                    budget -= 1157                _apply(lst, d)158        finally:159            con.close()160161162def parse_profusion_detail(html: str) -> dict:163    out: dict = {}164    title = ""165    for n in du.ld_nodes(html):166        t = n.get("@type")167        types = t if isinstance(t, list) else [t]168        if "RealEstateListing" in types:169            title = _html.unescape(n.get("name", "")).strip()170            if n.get("description"):171                out["description"] = _html.unescape(str(n["description"])).strip()172            offer = n.get("offers") or {}173            price = offer.get("price")174            try:175                price = float(price)176                if price >= 10_000:177                    out["price"] = price178            except (TypeError, ValueError):179                pass180            seller = offer.get("seller") or {}181            if seller.get("name"):182                out["broker_name"] = seller["name"]183            if seller.get("telephone"):184                out["broker_phone"] = str(seller["telephone"])185            break186    if title:187        out["title"] = title188        m = _NAME_RE.search(title)189        if m:190            type_phrase, loc = m.group(1).strip(), m.group(2).strip()191            out["property_type"] = type_phrase          # « Maison », « Terrain », « Condo »…192            # séparer « Ville (Secteur) » de l'adresse civique (après le tiret)193            parts = re.split(r"\s+[–—-]\s+", loc, maxsplit=1)194            city_block = parts[0].strip()195            if len(parts) > 1:196                out["address"] = parts[1].strip()197            ps = re.search(r"\(([^)]+)\)", city_block)198            out["city"] = re.sub(r"\s*\([^)]*\)", "", city_block).strip()199            if ps:200                out["sector"] = ps.group(1).strip()201202    # galerie complète203    imgs, seen = [], set()204    for u in _IMG_RE.findall(html):205        if u not in seen:206            seen.add(u)207            imgs.append(u)208    if imgs:209        out["images"] = imgs210211    # specs « Libellé: valeur »212    text = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", html)))213    details = {}214    for label, rx in (("Type de propriété", r"Type de propri[ée]t[ée]\s*:\s*([^:]{2,40}?)(?:\s{2,}|Chambres|Ann[ée]e|Superficie|$)"),215                      ("Chambres", r"Chambres\s*:\s*(\d+)"),216                      ("Salles de bain", r"Salles? de bain\s*:\s*(\d+)"),217                      ("Année de construction", r"Ann[ée]e\s*:\s*(\d{4})"),218                      ("Superficie habitable", r"Superficie\s*:\s*([\d  ,]+\s*(?:pi²|pi2|m²)?)")):219        m = re.search(rx, text, re.I)220        if m:221            details[label] = m.group(1).strip()222    ptype = details.get("Type de propriété", "")223    if ptype:224        out["property_type"] = ptype225    if details.get("Chambres"):226        out["bedrooms"] = int(re.search(r"\d+", details["Chambres"]).group())227    if details.get("Salles de bain"):228        out["bathrooms"] = int(re.search(r"\d+", details["Salles de bain"]).group())229    if details.get("Année de construction") and details["Année de construction"] != "0":230        out["year_built"] = int(details["Année de construction"])231    if details:232        out["details"] = {k: v for k, v in details.items() if v and v != "0"}233    return out234235236def _apply(lst: PropertyListing, d: dict) -> None:237    if not d:238        return239    # le vrai courtier (fiche) remplace le placeholder « Profusion Immobilier »240    if d.get("broker_name"):241        lst.broker_name = d["broker_name"]242    for f in ("title", "address", "city", "sector", "property_type",243              "description", "broker_phone"):244        if d.get(f) and not getattr(lst, f, ""):245            setattr(lst, f, d[f])246    if not lst.address and d.get("title"):247        lst.address = d["title"]248    for f in ("price", "bedrooms", "bathrooms", "year_built"):249        if d.get(f) is not None and getattr(lst, f, None) in (None, 0):250            setattr(lst, f, d[f])251    if d.get("images") and len(d["images"]) > len(lst.images):252        lst.images = d["images"]253    if d.get("details"):254        lst.details.update(d["details"])255
Files main
Menu

Theme