SPB Git

Repository Public

simplex.py 9.5 KB 221 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/simplex.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-10-0714#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/simplex.py : connecteur Simplex Immobilier (simpleximmobilier.com)91#   — agence/gestionnaire de ~600 logements à Trois-Rivières, Shawinigan et en92#   Mauricie (~25-30 annonces publiées à la fois). Site Astro dont le catalogue93#   vit dans un Supabase public : la RPC `get_public_rental_listings_page`94#   (clé publiable `sb_publishable_…` embarquée dans le bundle JS du site)95#   retourne TOUT en 1-2 requêtes JSON : titre, ville/secteur, type d'unité,96#   chambres/sdb, loyer, statut (available/coming_soon/reserved/rented),97#   date de disponibilité, description, inclusions, animaux, stationnement,98#   photos (bucket public `rental-listing-media`).99#   ⚠️ Aucune adresse civique publiée (même la RPC détail n'en expose pas) :100#   ville/secteur seulement, donc pas de géocodage fin possible.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import json105import os106107from ..schema import Listing108from .base import BaseConnector109110SB_URL = "https://tyrzkvwbiaadajwopdrj.supabase.co"111RPC_URL = f"{SB_URL}/rest/v1/rpc/get_public_rental_listings_page"112STORAGE_URL = f"{SB_URL}/storage/v1/object/public"113SITE = "https://simpleximmobilier.com"114# clé PUBLIABLE (anon) du site — surchargeable si Simplex la fait tourner115API_KEY = os.environ.get(116    "LOUKA_SIMPLEX_KEY", "sb_publishable_HT7wke-8-o_TUxMUeLjWbw_wsVK1FC4")117118PAGE = 100119_KEEP = {"available", "coming_soon"}120_STATUS_FR = {"available": "Disponible", "coming_soon": "Bientôt disponible"}121_PETS = {"oui": "oui", "non": "non"}122123124class SimplexConnector(BaseConnector):125    source_id = "simplex"126    request_delay = 0.8127128    def _rpc(self, offset: int) -> list[dict]:129        resp = self.post(RPC_URL, data=json.dumps({130            "p_search": None, "p_status": None, "p_location": None,131            "p_unit_type": None, "p_max_price": None, "p_pets": None,132            "p_parking": None, "p_sort": "recommended",133            "p_offset": offset, "p_limit": PAGE,134        }), headers={"apikey": API_KEY,135                     "Authorization": f"Bearer {API_KEY}",136                     "Content-Type": "application/json"})137        data = resp.json()138        if not isinstance(data, list):139            # clé révoquée / RPC renommée → dict d'erreur : erreur FRANCHE,140            # jamais un zéro silencieux (médiane 0.0 → indétectable sinon)141            raise RuntimeError(142                f"simplex : réponse RPC inattendue — {str(data)[:200]}")143        return data144145    def fetch(self) -> list[Listing]:146        rows: list[dict] = []147        offset = 0148        while True:149            batch = self._rpc(offset)150            rows.extend(batch)151            total = batch[0].get("total_count", 0) if batch else 0152            # la RPC plafonne côté serveur (~24 lignes/appel, quel que soit153            # p_limit) : avancer de la taille reçue, sinon la queue est sautée154            offset += len(batch)155            if not batch or offset >= total:156                break157        listings: dict[str, Listing] = {}158        for row in rows:159            if row.get("availability_status") not in _KEEP:160                continue161            lst = self._listing(row)162            if lst and lst.uid not in listings:163                listings[lst.uid] = lst164        return list(listings.values())165166    def _images(self, row: dict) -> list[str]:167        media = sorted(row.get("media") or [],168                       key=lambda m: (not m.get("isPrimary"),169                                      m.get("sortOrder") or 0))170        out = []171        for m in media:172            if m.get("bucket") and m.get("path"):173                out.append(f"{STORAGE_URL}/{m['bucket']}/{m['path']}")174        for p in [row.get("primary_image_path"),175                  *(row.get("gallery_paths") or [])]:176            if p and p.startswith("http") and p not in out:177                out.append(p)178        return out[:20]179180    def _listing(self, row: dict) -> Listing | None:181        price = row.get("rent_amount")182        status = row.get("availability_status") or ""183        avail_txt = _STATUS_FR.get(status, "")184        avail_date = (row.get("available_from") or "")[:10]185        if status == "coming_soon" and avail_date:186            avail_txt = f"{avail_txt} — à compter du {avail_date}"187        pets_raw = (row.get("pets_policy") or "").strip().lower()188        amen = [a for a in (row.get("inclusions") or []) +189                (row.get("features") or []) + (row.get("labels") or []) if a]190        details = {}191        if row.get("parking"):192            details["stationnement"] = str(row["parking"]).strip()193        if row.get("public_reference"):194            details["référence"] = row["public_reference"]195        if row.get("rent_note"):196            details["note loyer"] = row["rent_note"]197        return Listing(198            source=self.source_id,199            external_id=str(row.get("id") or row.get("slug")),200            url=f"{SITE}/logements-a-louer/{row.get('slug', '')}/",201            title=(row.get("title") or "").strip(),202            sector=(row.get("sector") or "").strip(),203            city=(row.get("city") or "").strip(),204            unit_type=(row.get("unit_type") or "").strip(),205            bedrooms=(float(row["bedrooms"])206                      if row.get("bedrooms") is not None else None),207            bathrooms=(float(row["bathrooms"])208                       if row.get("bathrooms") is not None else None),209            price=float(price) if price else None,210            price_label=(f"{price:,.0f} $/mois".replace(",", " ")211                         if price else ""),212            availability=avail_txt,213            availability_date=("now" if status == "available"214                               else (avail_date or None)),215            pets=_PETS.get(pets_raw.rstrip(" .!")),216            description=(row.get("description") or "")[:2000],217            amenities=amen[:30],218            details=details,219            images=self._images(row),220        )221
Files main
Menu

Theme