SPB Git

Repository Public

proprio_direct.py 8.8 KB 227 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/proprio_direct.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/proprio_direct.py : Proprio Direct (propriodirect.com)91#   L'inventaire (alimenté par le feed DDF de CREA) est servi par une API JSON92#   interne : POST https://propriodirect.com/fr/api/searchListings93#   Corps { "from": <offset> } ; 30 résultats/page, champ `total`. Chaque item94#   contient adresse, ville, région, prix, chambres, sdb, galerie photos et slug.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import os99100from .base import BaseConnector101from . import _detailutil as du102from ..schema import PropertyListing103104SITE = "https://propriodirect.com"105SEARCH_URL = f"{SITE}/fr/api/searchListings"106PAGE_SIZE = 30107MAX_PAGES = 300108DETAIL_LIMIT = int(os.environ.get("IMMOKA_PD_DETAIL_LIMIT", "400"))109110# tags source (feed DDF) -> caractéristiques lisibles111_TAG_LABELS = {112    "car_garage": "Garage", "car_parking": "Stationnement", "car_foyer": "Foyer",113    "car_piscine": "Piscine", "car_climatisation": "Climatisation",114    "car_sous_sol": "Sous-sol", "car_bord_eau": "Bord de l'eau",115    "prox_park": "Parc à proximité", "prox_ecole_primaire": "École primaire",116    "prox_ecole_secondaire": "École secondaire", "prox_transport": "Transport en commun",117    "prox_garderie": "Garderie", "prox_piste_cyclable": "Piste cyclable",118    "prox_hopital": "Hôpital", "prox_autoroute": "Autoroute",119    "new_price": "Nouveau prix",120}121122# genre (code CREA/DDF) -> vocabulaire brut (finalize() normalise)123_GENRE = {124    "PP": "Maison", "ET": "Maison", "MA": "Maison", "PL": "Maison",125    "CO": "Condo", "AP": "Condo", "LO": "Condo",126    "DX": "Duplex", "TX": "Triplex", "QX": "Quadruplex", "MX": "Multiplex",127    "TE": "Terrain", "TR": "Terrain",128    "CH": "Chalet", "FE": "Fermette/Agricole", "FR": "Fermette/Agricole",129    "CM": "Commercial", "IN": "Commercial",130}131132133class ProprioDirectConnector(BaseConnector):134    source_id = "proprio_direct"135    request_delay = 0.4136    use_detail_cache = False137138    def _headers(self) -> dict:139        return {140            "Accept": "application/json",141            "Content-Type": "application/json",142            "Origin": SITE,143            "Referer": f"{SITE}/propriete-a-vendre/",144        }145146    def fetch(self) -> list[PropertyListing]:147        out: list[PropertyListing] = []148        seen: set[str] = set()149        offset = 0150        for _ in range(MAX_PAGES):151            try:152                data = self.post(SEARCH_URL, headers=self._headers(),153                                 json={"from": offset,154                                       "includeGeoJson": False}).json()155            except Exception:156                break157            items = data.get("listings", []) if isinstance(data, dict) else []158            if not items:159                break160            for it in items:161                lst = self._to_listing(it)162                if lst and lst.uid not in seen:163                    seen.add(lst.uid)164                    out.append(lst)165            total = data.get("total") or 0166            offset += PAGE_SIZE167            if offset >= total:168                break169        # fiche détail : description (galerie déjà complète via l'API)170        du.enrich(self, out, DETAIL_LIMIT, _parse_pd_detail, key="v2")171        return out172173    def _to_listing(self, it: dict) -> PropertyListing | None:174        rid = it.get("id")175        if not rid or it.get("sold") or not it.get("forSale", True):176            return None177        cents = it.get("priceInCents")178        price = (cents / 100.0) if isinstance(cents, (int, float)) and cents > 0 else None179        slug = it.get("slugURLFr") or it.get("slugURL") or ""180        url = f"{SITE}{slug}" if slug.startswith("/") else (slug or SITE)181        geo = it.get("geoLocation") or {}182183        return PropertyListing(184            source=self.source_id,185            external_id=str(rid),186            url=url,187            title=it.get("addressLine", ""),188            address=it.get("addressLine", ""),189            sector=it.get("cityNeighbourhoodText", "") or "",190            city=it.get("cityName", ""),191            region=it.get("regionName", ""),192            property_type=_GENRE.get((it.get("genre") or "").upper(),193                                     it.get("genreName", "")),194            price=price,195            price_label=it.get("priceText", "") or "",196            bedrooms=_pos_int(it.get("numberOfRooms")),197            bathrooms=_pos_int(it.get("numberOfBathrooms")),198            mls=str(rid),199            images=list(it.get("photosOriginal") or it.get("photosSmall") or []),200            lat=geo.get("lat"),201            lng=geo.get("lon"),202            broker_name="Proprio Direct",203            features=[_TAG_LABELS[t] for t in (it.get("tags") or []) if t in _TAG_LABELS],204            details={"postal_code": it.get("postalCode", "")},205        )206207208def _parse_pd_detail(html: str) -> dict:209    """Fiche Proprio Direct : description + caractéristiques Centris détaillées210    (photos déjà fournies par l'API)."""211    out: dict = {}212    desc = du.ld_description(html)213    if desc:214        out["description"] = desc215    det = du.centris_details(du.flatten(html))216    if det:217        out.setdefault("details", {}).update(det)218    return out219220221def _pos_int(v):222    try:223        n = int(v)224        return n if n > 0 else None225    except (TypeError, ValueError):226        return None227
Files main
Menu

Theme