Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/kggroup.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2713# Last Modified : 2026-08-2714#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 (Québec + expansion Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/kggroup.py : connecteur KG Group (myrental.ca)91# Gestionnaire familial torontois (~4 700 suites — 7 tours à Midtown,92# North York, Yonge & Sheppard). Le site est un Rentsync « nouvelle93# génération » (SPA Vue servie par cdn.rentsync.com/site/kg_rebuild) : PAS94# le flux LiftSystem classique (api.theliftsystem.com, cf. liftsystem.py)95# mais l'API interne « website-gateway » découverte dans les bundles JS :96# https://website-gateway-cdn.rentsync.com/v1/kg_rebuild/97# properties -> 7 immeubles (adresse, GPS, quartier,98# overview HTML, politique animaux…)99# properties/<id>/unit-summary -> unités DISPONIBLES en direct100# (typeName, bed, bath, sqFt, rate)101# properties/<id>/photos -> galerie (fichiers S3 lws_lift, servis102# en https://s3.amazonaws.com/lws_lift/103# kggroup/images/gallery/full/<image>)104# properties/<id>/amenities -> commodités nommées105# Aucun anti-bot, pas de clé : l'API répond à un simple GET JSON.106# Une annonce PAR TYPE D'UNITÉ DISPONIBLE (groupé sur typeName, ex. « 1A »),107# prix plancher réel du groupe ; repli « une annonce par immeuble » SANS108# prix quand aucune unité n'est affichée (rien d'inventé). unit-summary est109# interrogé en direct à chaque synchronisation (c'est la donnée vivante) ;110# photos + commodités passent par le cache BD self.detail() (clé = champ111# `modified` de l'immeuble). Toutes les adresses sont à Toronto (North York,112# Midtown… = quartiers) : city = « Toronto », sector = neighbourhood du flux.113#114# Expansion Ontario — GATÉE par LOUKA_ONTARIO=1 : sans la variable, le115# connecteur est `disabled` et exclu du registre (zéro impact prod QC).116# -----------------------------------------------------------------------------117from __future__ import annotations118119import html120import os121import re122123from bs4 import BeautifulSoup124125from ..schema import Listing, normalize_unit_type126from .base import BaseConnector127128SITE = "https://www.myrental.ca"129GATEWAY = "https://website-gateway-cdn.rentsync.com/v1/kg_rebuild"130# galerie S3 du client Rentsync (préfixe du compte : « kggroup »)131IMG_BASE = "https://s3.amazonaws.com/lws_lift/kggroup/images/gallery/full"132133# Gate expansion Ontario : le connecteur reste hors registre tant que la134# variable d'environnement LOUKA_ONTARIO=1 n'est pas posée.135_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"136137138class KgGroupConnector(BaseConnector):139 source_id = "kggroup"140 request_delay = 1.0141 disabled = not _ONTARIO # gate expansion Ontario (LOUKA_ONTARIO=1)142 max_properties = 15 # garde-fou (7 immeubles aujourd'hui)143 max_images = 20144145 def _api(self, path: str):146 return self.get(f"{GATEWAY}/{path}",147 headers={"Accept": "application/json",148 "Referer": SITE + "/"}).json().get("data")149150 def fetch(self) -> list[Listing]:151 props = self._api("properties") or []152153 listings: list[Listing] = []154 count = 0155 for p in props:156 try:157 if (p.get("status") or "").lower() != "enabled":158 continue159 if count >= self.max_properties:160 break161 count += 1162 listings.extend(self._property_listings(p))163 except Exception:164 continue165 return listings166167 # -- annonces d'un immeuble (une par type d'unité disponible) ---------------168 def _property_listings(self, p: dict) -> list[Listing]:169 pid = str(p.get("id"))170 perma = (p.get("permaLink") or "").strip()171 url = f"{SITE}/apartments-for-rent/{perma}" if perma else SITE172 name = (p.get("buildingName") or "").strip()173174 # adresse complète : rue + Toronto + « ON <postal> » — le parc KG est175 # entièrement torontois (North York/Midtown = quartiers, pas villes)176 street = " ".join(x for x in ((p.get("streetNumber") or "").strip(),177 (p.get("streetName") or "").strip()) if x)178 postal = (p.get("postal") or "").strip()179 city = "Toronto"180 sector = (p.get("neighbourhood") or "").strip()181 full_addr = ", ".join(x for x in (street, city) if x) + ", ON"182 if postal:183 full_addr += f" {postal}"184185 # coordonnées GPS du flux (finalize() valide la bbox Ontario)186 try:187 lat = float(p.get("latitude")) if p.get("latitude") else None188 lng = float(p.get("longitude")) if p.get("longitude") else None189 except (TypeError, ValueError):190 lat = lng = None191192 # politique animaux : champs structurés du flux — rien d'inventé193 pets = None194 if p.get("petsNotAllowed"):195 pets = "non"196 elif p.get("petFriendly"):197 pets = "oui"198 elif p.get("petsCats") or p.get("petsSmallDogs") \199 or p.get("petsLargeDogs"):200 pets = "conditions"201202 # description : overview HTML doublement échappé du flux203 desc = BeautifulSoup(html.unescape(p.get("buildingOverview") or ""),204 "html.parser").get_text(" ", strip=True)[:600]205206 details: dict = {}207 phone = (p.get("phone") or "").strip()208 if phone:209 details["contact"] = {"phone": phone}210211 # photos + commodités via le cache BD : revisitées seulement quand212 # l'immeuble est modifié côté Rentsync213 feed_key = str(p.get("modified") or "")214 d = self.detail(pid, feed_key, lambda: self._fetch_media(pid))215 images = (d.get("images") or [])[: self.max_images]216 amenities = (d.get("amenities") or [])[:25]217218 common = dict(219 source=self.source_id, url=url, address=full_addr, sector=sector,220 city=city, province="ON", pets=pets, description=desc,221 amenities=amenities, images=images, lat=lat, lng=lng,222 details=details,223 )224225 # unités disponibles EN DIRECT (unit-summary) — la donnée vivante226 units = []227 try:228 summary = self._api(f"properties/{pid}/unit-summary") or {}229 units = (((summary.get("availableSummary") or {})230 .get("available") or {}).get("units")) or []231 except Exception:232 units = []233234 # une annonce par TYPE d'unité disponible (groupé sur typeName)235 groups: dict[str, dict] = {}236 for u in units:237 if u.get("available") != 1 or u.get("hideSuiteTypeWebsite"):238 continue239 key = str(u.get("typeName") or240 f"{u.get('bed')}-{u.get('bath')}-{u.get('sqFt')}")241 g = groups.setdefault(key, {"units": [], "bed": u.get("bed"),242 "bath": u.get("bath"),243 "sqft": u.get("sqFt")})244 g["units"].append(u)245246 out: list[Listing] = []247 for key, g in groups.items():248 rates = []249 for u in g["units"]:250 if u.get("hideRateWebsites"):251 continue252 try:253 r = float(u.get("rate") or 0)254 except (TypeError, ValueError):255 r = 0.0256 if r > 0:257 rates.append(r)258 price = min(rates) if rates else None259 beds = g["bed"]260 try:261 beds = float(beds) if beds is not None else None262 except (TypeError, ValueError):263 beds = None264 baths = g["bath"]265 try:266 baths = float(baths) if baths else None267 except (TypeError, ValueError):268 baths = None269 area = None270 try:271 v = float(g.get("sqft") or 0)272 if 80 <= v <= 20000:273 area = v274 except (TypeError, ValueError):275 pass276 n = len(g["units"])277 slug = re.sub(r"[^a-z0-9]+", "-", key.lower()).strip("-")278 out.append(Listing(279 external_id=f"{pid}-{slug or 'u'}",280 title=f"{name} — Suite {key}" if name else f"Suite {key}",281 unit_type=("Studio" if beds == 0 else normalize_unit_type(282 f"{int(beds)} chambres") if beds is not None else ""),283 bedrooms=beds,284 bathrooms=baths,285 price=price,286 price_label=(f"À partir de {price:.0f} $ /mois"287 if price is not None and n > 1288 else f"{price:.0f} $ /mois"289 if price is not None else ""),290 availability=(f"{n} unités disponibles" if n > 1291 else "Unité disponible"),292 area_sqft=area,293 **common,294 ))295 if out:296 return out297298 # repli : une annonce par immeuble — aucun prix inventé299 return [Listing(300 external_id=pid,301 title=name,302 unit_type="",303 availability="Aucune unité disponible",304 **common,305 )]306307 # -- médias : galerie S3 + commodités (endpoints secondaires) ---------------308 def _fetch_media(self, pid: str) -> dict:309 out: dict = {"images": [], "amenities": []}310 try:311 photos = self._api(f"properties/{pid}/photos") or []312 except Exception:313 photos = []314 images: list[str] = []315 for ph in sorted(photos, key=lambda x: (x or {}).get("orderBy") or 0):316 if not ph.get("active"):317 continue318 f = (ph.get("image") or "").strip()319 if not f:320 continue321 u = f"{IMG_BASE}/{f}"322 if u not in images:323 images.append(u)324 out["images"] = images[: self.max_images]325326 try:327 ams = self._api(f"properties/{pid}/amenities") or []328 except Exception:329 ams = []330 amenities: list[str] = []331 for a in ams:332 t = (a.get("name") or "").strip() if isinstance(a, dict) else ""333 if t and (a.get("status") or "enabled") == "enabled" \334 and t not in amenities:335 amenities.append(t)336 out["amenities"] = amenities[:25]337 return out338