Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/rakotta.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2514#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/rakotta.py : connecteur Rakotta Real Estate (rakotta.com)91# Centre-ville de Montréal — Appartements Dorchester (1555 René-Lévesque O.),92# Gramercy Residences (1900-1950 Sherbrooke O.) et Le 2100 (2100 boul. de93# Maisonneuve O.). Le site rakotta.com est une SPA Rentsync/LiftSystem94# (client « rakotta_rebuild », clientId 484 — mêmes gens que95# appartementsdorchester.com et residencesgramercy.com) ; l'API passerelle96# publique website-gateway.rentsync.com/v1/rakotta_rebuild expose :97# - /properties?findBy[status]=enabled : les immeubles actifs (adresse,98# intersection, contact, stationnement) ;99# - /units?where=status~in:enabled&limit=750 : TOUTES les unités (id100# stable, numéro, prix, pi², chambres, sdb, étage, date de dispo,101# drapeaux furnished/shortTerm et durée de bail leaseTerm) ;102# - /photos?where=buildingId~in:<ids> : galeries (mainGallery), fichiers103# servis par assets.rentsync.com/appartements_dorchester/images/gallery/.104# ⚠️ Rakotta fait aussi du meublé à bail flexible (1 à 12 mois) : seuls les105# BAUX 12 MOIS sont conservés (leaseTerm == "12-month", shortTerm == 0) —106# le meublé 12 mois reste admissible (furnished=True). Les unités107# d'immeubles absents de /properties (immeubles désactivés) sont exclues.108# -----------------------------------------------------------------------------109from __future__ import annotations110111import html as _html112import re113114from ..schema import Listing115from .base import BaseConnector116117GATEWAY = "https://website-gateway.rentsync.com/v1/rakotta_rebuild"118SITE = "https://www.rakotta.com"119ASSETS = ("https://assets.rentsync.com/appartements_dorchester"120 "/images/gallery/full/")121122_TAG_RE = re.compile(r"<[^>]+>")123_WS_RE = re.compile(r"\s+")124_LEASE_12_RE = re.compile(r"^\s*12[\s-]*month", re.I)125126127def _num(v) -> float | None:128 try:129 return float(v)130 except (TypeError, ValueError):131 return None132133134class RakottaConnector(BaseConnector):135 source_id = "rakotta"136 request_delay = 0.6137 max_images = 10138139 def _api(self, path: str) -> list:140 data = self.get(f"{GATEWAY}/{path}").json()141 out = data.get("data") if isinstance(data, dict) else data142 return out if isinstance(out, list) else []143144 def fetch(self) -> list[Listing]:145 props = {p.get("id"): p for p in146 self._api("properties?findBy%5Bstatus%5D=enabled")}147 units = self._api("units?where=status~in:enabled&limit=750")148149 # galerie par immeuble (une petite requête par immeuble actif)150 photos: dict[int, list[str]] = {}151 for bid in props:152 bucket: list[str] = []153 try:154 rows = self._api(f"photos?where=buildingId~in:{bid}"155 f"&limit={self.max_images * 2}")156 except Exception:157 rows = []158 for ph in rows:159 if not ph.get("active") or not ph.get("image"):160 continue161 if len(bucket) < self.max_images:162 bucket.append(ASSETS + ph["image"])163 photos[bid] = bucket164165 listings: list[Listing] = []166 for u in units:167 try:168 lst = self._listing(u, props, photos)169 if lst:170 listings.append(lst)171 except Exception:172 continue # une unité ne bloque pas le reste173174 # dédup par external_id (sécurité)175 uniq: dict[str, Listing] = {}176 for lst in listings:177 uniq.setdefault(lst.external_id, lst)178 return list(uniq.values())179180 # -- une annonce par unité disponible (bail 12 mois seulement) --------------181 def _listing(self, u: dict, props: dict, photos: dict) -> Listing | None:182 if not u.get("available"):183 return None184 prop = props.get(u.get("buildingId"))185 if not prop:186 return None # immeuble désactivé : exclu187 # long terme seulement : bail 12 mois, pas de court terme188 if u.get("shortTerm"):189 return None190 lease = str(u.get("leaseTerm") or "")191 if lease and not _LEASE_12_RE.match(lease):192 return None # bail 3/6 mois (mid-term) : exclu193194 ext_id = str(u.get("id") or "")195 if not ext_id:196 return None197 num = str(u.get("number") or "").strip().lstrip("#")198 bname = _WS_RE.sub(" ", str(prop.get("buildingName") or "")).strip()199200 bed = int(_num(u.get("bed")) or 0)201 bath = _num(u.get("bath"))202 unit_type = "Studio" if bed == 0 else f"{bed + 2}½"203204 price = _num(u.get("rateMin")) or _num(u.get("rate"))205 if price is not None and not 100 <= price <= 20000:206 price = None207 area = _num(u.get("sqFtMin")) or _num(u.get("sqFt"))208 if area is not None and not 80 <= area <= 20000:209 area = None210211 dispo = str(u.get("availabilityDate") or "").strip()212 availability = f"Libre le {dispo}" if dispo else "Disponible"213214 furnished = None215 if u.get("furnished"):216 furnished = True217 elif u.get("unfurnished"):218 furnished = False219220 # description : HTML doublement encodé par l'API (<p>…)221 desc = _html.unescape(_html.unescape(str(u.get("description") or "")))222 desc = _WS_RE.sub(" ", _TAG_RE.sub(" ", desc)).strip()223 facts = " — ".join(x for x in [224 str(u.get("typeName") or ""),225 f"{area:g} pi²" if area else "",226 f"étage {u['floor']}" if str(u.get("floor") or "").strip()227 else "",228 f"{bed} chambre(s)" if bed else "",229 f"{bath:g} salle(s) de bain" if bath else "",230 "bail 12 mois"] if x)231 desc = f"{desc}\n{facts}" if desc else facts232233 details: dict = {"building": bname, "bedrooms": bed,234 "lease_term": "12 mois"}235 floor = str(u.get("floor") or "").strip()236 if floor.isdigit():237 details["floor"] = int(floor)238 phone = str(prop.get("phone") or "").strip()239 if phone:240 details["contact"] = {"phone": phone}241242 address = ", ".join(x for x in [243 " ".join(x for x in [str(prop.get("streetNumber") or "").strip(),244 str(prop.get("streetName") or "").strip()]245 if x),246 "Montréal",247 str(prop.get("postal") or "").strip()] if x)248249 return Listing(250 source=self.source_id,251 external_id=ext_id,252 url=f"{SITE}/properties/{prop.get('permaLink')}",253 title=(f"{bname} — Unité {num}" if num else bname),254 address=address,255 sector="Centre-ville",256 city="Montréal",257 unit_type=unit_type,258 bedrooms=float(bed),259 bathrooms=bath,260 price=price,261 availability=availability,262 area_sqft=area,263 furnished=furnished,264 description=desc[:900],265 details=details,266 images=list(photos.get(u.get("buildingId")) or []),267 )268