SPB Git

Repository Public

proprio_direct.py 11.5 KB 283 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/proprio_direct.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/proprio_direct.py : Proprio Direct (propriodirect.com) — LOCATION91#   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>, "filter": {"rentOrSale": "rent"} } — le filtre94#   côté API fonctionne (~260 locations vs ~3200 annonces au total) ; 3095#   résultats/page, champ `total`. Chaque item porte forRent/forSale/sold,96#   le loyer en cents (rentPriceInCents, rentPriceFrequency), adresse, ville,97#   région, chambres, sdb, GPS, tags et galerie photos. On ne garde que le98#   volet RÉSIDENTIEL (tag « residential ») : les locaux commerciaux et99#   industriels (loyer en $/pi²/an) sont écartés. Adapté du connecteur100#   « à vendre » d'Immo-Ka (agent-courtage/immoka).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import os105import re106107from ..schema import Listing108from .base import BaseConnector109110from . import _detailutil as du111112SITE = "https://propriodirect.com"113SEARCH_URL = f"{SITE}/fr/api/searchListings"114PAGE_SIZE = 30115MAX_PAGES = 60                       # garde-fou (~260 locations = 9 pages)116DETAIL_LIMIT = int(os.environ.get("LOUKA_PD_DETAIL_LIMIT", "400"))117118# tags source (feed DDF) -> caractéristiques lisibles119_TAG_LABELS = {120    "car_garage": "Garage", "car_parking": "Stationnement", "car_foyer": "Foyer",121    "car_piscine": "Piscine", "car_climatisation": "Climatisation",122    "car_sous_sol": "Sous-sol", "car_bord_eau": "Bord de l'eau",123    "prox_park": "Parc à proximité", "prox_ecole_primaire": "École primaire",124    "prox_ecole_secondaire": "École secondaire", "prox_transport": "Transport en commun",125    "prox_garderie": "Garderie", "prox_piste_cyclable": "Piste cyclable",126    "prox_hopital": "Hôpital", "prox_autoroute": "Autoroute",127    "new_price": "Nouveau prix",128}129130131class ProprioDirectConnector(BaseConnector):132    source_id = "proprio_direct"133    request_delay = 0.4134135    def _headers(self) -> dict:136        return {137            "Accept": "application/json",138            "Content-Type": "application/json",139            "Origin": SITE,140            "Referer": f"{SITE}/propriete-a-louer/",141        }142143    def fetch(self) -> list[Listing]:144        out: list[Listing] = []145        seen: set[str] = set()146        offset = 0147        for _ in range(MAX_PAGES):148            try:149                data = self.post(SEARCH_URL, headers=self._headers(),150                                 json={"from": offset,151                                       "includeGeoJson": False,152                                       "filter": {"rentOrSale": "rent"}}).json()153            except Exception:154                break155            items = data.get("listings", []) if isinstance(data, dict) else []156            if not items:157                break158            for it in items:159                lst = self._to_listing(it)160                if lst and lst.uid not in seen:161                    seen.add(lst.uid)162                    out.append(lst)163            total = data.get("total") or 0164            offset += PAGE_SIZE165            if offset >= total:166                break167        # fiche détail : description (la galerie est déjà complète via l'API)168        du.enrich(self, out, DETAIL_LIMIT, _parse_pd_detail, key="v3")169        return out170171    def _to_listing(self, it: dict) -> Listing | None:172        rid = it.get("id")173        tags = it.get("tags") or []174        # location résidentielle seulement (ceinture + bretelles : le filtre175        # API renvoie déjà uniquement des locations, on revalide chaque item)176        if (not rid or it.get("sold") or not it.get("forRent")177                or "residential" not in tags):178            return None179        # loyer mensuel : rentPriceInCents (fallback priceInCents si le feed180        # met le loyer dans le prix principal) — on écarte les baux annuels181        # au pi² qui se seraient glissés dans le volet résidentiel182        freq = it.get("rentPriceFrequency") or "monthly"183        if freq != "monthly":184            return None185        cents = it.get("rentPriceInCents") or it.get("priceInCents")186        price = (cents / 100.0) if isinstance(cents, (int, float)) and cents > 0 else None187188        slug = it.get("slugURLFr") or it.get("slugURL") or ""189        url = f"{SITE}{slug}" if slug.startswith("/") else (slug or SITE)190        geo = it.get("geoLocation") or {}191192        # type d'unité : nb de chambres (normalisé n+2 ½ par finalize()) ;193        # le genre Loft/Studio (LS) sans chambre est un studio194        genre = (it.get("genre") or "").upper()195        rooms = _pos_int(it.get("numberOfRooms"))196        unit_type = f"{rooms} chambres" if rooms else ("Studio" if genre == "LS" else "")197198        details: dict = {"Courtier": "Proprio Direct"}199        if it.get("genreName"):200            details["Type"] = it["genreName"]201        if it.get("regionName"):202            details["Région"] = it["regionName"]203        baths = _pos_int(it.get("numberOfBathrooms"))204        if baths:205            details["Salles de bain"] = str(baths)206        if it.get("postalCode"):207            details["Code postal"] = it["postalCode"]208209        return Listing(210            source=self.source_id,211            external_id=str(rid),212            url=url,213            title=it.get("addressLine", ""),214            address=it.get("addressLine", ""),215            sector=it.get("neighbourhood", "") or "",216            city=it.get("cityName", ""),217            unit_type=unit_type,218            price=price,219            price_label=it.get("rentPriceText", "") or "",220            amenities=[_TAG_LABELS[t] for t in tags if t in _TAG_LABELS],221            details=details,222            images=list(it.get("photosOriginal") or it.get("photosSmall") or []),223            lat=geo.get("lat"),224            lng=geo.get("lon"),225        )226227228# libellés des « Points saillants » d'une fiche Proprio Direct — la page les229# rend en liste « libellé | valeur » stricte (contrairement aux fiches Centris,230# d'où un parseur dédié plutôt que du.centris_details qui appariait de travers)231_PD_LABELS = [232    "Année de construction", "Superficie habitable", "Niveau",233    "Équipement disponible", "Zonage", "Mode de chauffage",234    "Énergie pour le chauffage", "Approvisionnement en eau",235    "Système d'égouts", "Restrictions/Permissions",236    "Garage", "Piscine", "Foyer-Poêle", "Meublé", "Animaux",237    "Disponibilité", "Date d'emménagement", "Bail",238]239_PD_SECTIONS = {"points saillants", "détails", "pièces", "inclus", "exclus",240                "style de vie", "description"}241242243def _pd_details(text: str) -> dict:244    """Paires « libellé | valeur » des Points saillants (ordre strict)."""245    stop = {l.lower() for l in _PD_LABELS} | _PD_SECTIONS246    out: dict = {}247    for label in _PD_LABELS:248        m = re.search(re.escape(label) + r"\s*\|\s*([^|]{1,90})", text)249        if m:250            val = m.group(1).strip(" |")251            if val and val.lower() not in stop:252                out[label] = val253    return out254255256def _parse_pd_detail(html: str) -> dict:257    """Fiche Proprio Direct : description + points saillants258    (photos déjà fournies par l'API)."""259    out: dict = {}260    desc = du.ld_description(html)261    # le JSON-LD des fiches sans texte retombe sur la description « méta »262    # générique (« … | No. Inscription 12345678 | Proprio Direct ») — on l'écarte263    if desc and "No. Inscription" not in desc:264        out["description"] = desc265    det = _pd_details(du.flatten(html))266    if det:267        out.setdefault("details", {}).update(det)268        # « Animaux permis sous conditions » / « Animaux non admis »…269        restr = det.get("Restrictions/Permissions", "").lower()270        if "animaux" in restr:271            out["pets"] = ("conditions" if "condition" in restr272                           else "non" if ("non" in restr or "pas" in restr)273                           else "oui")274    return out275276277def _pos_int(v):278    try:279        n = int(v)280        return n if n > 0 else None281    except (TypeError, ValueError):282        return None283
Files main
Menu

Theme