SPB Git

Repository Public

rivero.py 11.2 KB 277 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/rivero.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# 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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/rivero.py : connecteur Le Rivero (lerivero.ca — Québec,91#   rue Bourdages, aux abords de la rivière Saint-Charles).92#   Le sélecteur de plans est un embed RealVuu (app.realvuu.com) dont la page93#   contient toutes les unités en JSON (numéro, pièces, prix, disponibilité,94#   plans/images). Phase 1 louée; phase 2 (livraison été 2028) en prélocation.95#   Garde-fou : si toutes les unités « disponibles » affichent un prix96#   identique (placeholder), le prix n'est pas retenu.97#   DÉSACTIVÉ 2026-08-18 : app.realvuu.com hors-ligne depuis le 2026-08-1098#   (DNS NXDOMAIN). Réactiver (disabled=False) si le widget RealVuu revit.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import json103import re104105from ..schema import Listing, infer_city106from .base import BaseConnector107108RV_URL = "https://app.realvuu.com/fr/external/immeubles-simard/rivero/plans"109SITE_URL = "https://www.lerivero.ca/plans/"110SECTOR = "Vanier (rivière Saint-Charles)"111112113def _extract_json_array(html: str, key: str) -> list:114    """Extrait le plus grand tableau JSON `"key":[...]` de la page RealVuu.115116    La clé peut apparaître plusieurs fois (souvent vide ailleurs) : on garde117    l'occurrence contenant le plus d'éléments.118    """119    dec = json.JSONDecoder()120    needle = f'"{key}":['121    best: list = []122    start = 0123    while True:124        i = html.find(needle, start)125        if i == -1:126            break127        try:128            arr, _ = dec.raw_decode(html[i + len(needle) - 1:])129            if isinstance(arr, list) and len(arr) > len(best):130                best = arr131        except Exception:132            pass133        start = i + len(needle)134    return best135136137def _unit_type_from_rooms(rooms: float, rooms_bed: int = 0) -> str:138    if not rooms:139        # repli structuré : n chambres -> (n+2)½ (convention Lou-Ka)140        if rooms_bed:141            n = int(rooms_bed) + 2142            return "6½+" if n >= 6 else f"{n}½"143        return ""144    if rooms <= 1:145        return "Studio"146    return f"{int(rooms)}½"147148149class RiveroConnector(BaseConnector):150    source_id = "rivero"151    request_delay = 0.6152    disabled = True   # widget RealVuu (app.realvuu.com) hors-ligne depuis 2026-08-10153154    def fetch(self) -> list[Listing]:155        html = self.get(RV_URL).text156157        units = _extract_json_array(html, "units")158        buildings = {b.get("buildingId"): b159                     for b in _extract_json_array(html, "buildings")}160        # étages : floorId -> numéro (structuré, pour details.floor)161        floors = {f.get("floorId"): f.get("number")162                  for f in _extract_json_array(html, "floors")163                  if f.get("floorId")}164165        avail = [u for u in units166                 if u.get("availability") == "AVAILABLE"167                 and u.get("rental")168                 and u.get("typeType") == "APARTMENT"169                 and u.get("segment") in ("RESIDENTIAL", "", None)170                 and u.get("isMarketable", True)]171        if not avail:172            return []173174        # Garde-fou prix placeholder : prix unique pour des types différents175        prices = {u.get("rentalPrice") for u in avail}176        rooms_set = {u.get("rooms") for u in avail}177        placeholder = len(prices) == 1 and len(rooms_set) > 1178179        listings: list[Listing] = []180        for u in avail:181            try:182                b = buildings.get(u.get("buildingId"), {})183                bname = (b.get("name") or "").strip()184                address = (u.get("address") or b.get("address") or "").strip()185                # compléter l'adresse avec ville + code postal (structurés)186                city_src = (u.get("city") or b.get("city") or "").strip()187                postal = (u.get("postalCode") or "").strip()188                if address and city_src:189                    address = f"{address}, {city_src}" \190                              + (f", QC {postal}" if postal else "")191                number = str(u.get("number") or "").strip()192                unit_type = _unit_type_from_rooms(u.get("rooms") or 0,193                                                  u.get("roomsBed") or 0)194195                price = None196                price_label = ""197                rp = u.get("rentalPrice") or 0198                if rp and not placeholder and 100 <= rp <= 20000:199                    price = float(rp)200                    price_label = f"{rp} $/mois"201202                availability = "Disponible"203                if u.get("futureAvailability"):204                    availability = f"Disponible : {u['futureAvailability']}"205                if "phase 2" in bname.lower():206                    availability = "Phase 2 — prélocation (livraison été 2028)"207208                images: list[str] = []209                for ti in (u.get("typeImages") or []):210                    if ti.get("fullUrl"):211                        images.append(ti["fullUrl"])212                for im in (u.get("images") or []):213                    if isinstance(im, dict) and im.get("fullUrl"):214                        images.append(im["fullUrl"])215                if u.get("floorPlanImageUrl"):216                    images.append(u["floorPlanImageUrl"])217                images = list(dict.fromkeys(images))218219                desc = []220                if u.get("unitSize"):221                    desc.append(f"{u['unitSize']} pi²")222                if u.get("roomsBed"):223                    desc.append(f"{u['roomsBed']} chambre(s)")224                if u.get("roomsOffice"):225                    desc.append(f"{u['roomsOffice']} espace(s) bureau")226                if u.get("roomsBath"):227                    desc.append(f"{u['roomsBath']} salle(s) de bain")228                if u.get("balconySize"):229                    desc.append(f"Balcon/loggia {u['balconySize']} pi²")230                if u.get("orientation"):231                    desc.append(f"Orientation {u['orientation']}")232                if bname:233                    desc.append(bname)234235                # superficie structurée (mesures IMPERIAL -> déjà en pi²)236                area = None237                us = u.get("unitSize") or 0238                if 80 <= us <= 20000:239                    area = float(us)240241                # champs structurés : étage, coordonnées242                details: dict = {}243                floor_no = floors.get(u.get("floorId"))244                if isinstance(floor_no, int) and 0 < floor_no <= 60:245                    details["floor"] = floor_no246                lat = u.get("latitude")247                lng = u.get("longitude")248                if not (lat and lng):249                    lat, lng = b.get("latitude"), b.get("longitude")250251                listings.append(Listing(252                    source=self.source_id,253                    external_id=u.get("unitId") or f"{bname}-{number}",254                    url=SITE_URL,255                    title=f"Le Rivero — Unité {number}"256                          f"{' (' + unit_type + ')' if unit_type else ''}",257                    address=address,258                    sector=SECTOR,259                    city=infer_city(SECTOR, default="Québec"),260                    unit_type=unit_type,261                    price=price,262                    price_label=price_label,263                    availability=availability,264                    area_sqft=area,265                    description=" | ".join(desc),266                    amenities=["Eau chaude incluse", "Électricité et chauffage",267                               "Air climatisé", "Internet inclus"],268                    details=details,269                    images=images,270                    lat=float(lat) if lat else None,271                    lng=float(lng) if lng else None,272                ))273            except Exception:274                continue275276        return listings277
Files main
Menu

Theme